Part Number Hot Search : 
BD6757KN MAJ120A 1N5928B LC1D32P7 A2615 F2812 LX8384 A101L
Product Description
Full Text Search
 

To Download 28122 Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
  basic stamp syntax and reference manual version 2.2
warranty parallax inc. warrants its products against defects in material s and workmanship for a period of 90 days from receipt of product. if you discover a defect, parallax inc. will, at its option, repair or replace the merchandise, or refund the purchas e price. before returning the product to parallax, call for a return merchandise authorization (rma) number. write the rma number on the outside of the box used to return the merchandise to parallax. please enclose the following along with the returned merchandise: your name, telephone number, shipping address, and a description of the problem. parallax will return your product or its replace ment using the same shipping method used to ship the product to parallax. 14-day money-back guarantee if, within 14 days of having received your product, you find th at it does not suit your needs, you may return it for a full refund. parallax inc. will refund the purchase price of the pr oduct, excluding shipping/handling costs. this guarantee is void if the product has been altered or damaged. see the warranty section above for instructions on returning a product to parallax. copyrights and trademarks this documentation is copyright 1994-2005 by parallax inc. by downlo ading or obtaining a pr inted copy of this documentation or software you agree that it is to be used exclusively with parallax products. any other uses are not permitted and may represent a violation of parallax copyrights, legally punishab le according to federal copyright or intellectual property laws. any duplication of this documentation fo r commercial uses is expre ssly prohibited by parallax inc. duplication for educat ional use is permitted, subject to the follow ing conditions of duplication: parallax inc. grants th e user a conditional right to download, duplic ate, and distribute this te xt without parallax?s permission. this right is based on the following conditions: the te xt, or any portion thereof, may not be duplicat ed for commercial use; it may be duplicated only for educational purposes when used solely in conjunction with parallax products, and the user may recover from the student only the cost of duplication. this text is available in printed format fr om parallax inc. because we print the te xt in volume, the consumer price is often less than typical retail duplication charges. basic stamp, stamps in class, board of education, boe-bot, todder, sumobot, an d sx-key are registered trademarks of parallax, inc. if you decide to use registered trademarks of parallax inc. on your web page or in printed material, you must state that ?(registered trademar k) is a registered trademark of parallax inc.? upon the first appearance of the trademark name in each printed document or web page. homework board, parallax, and the parallax logo are trademarks of parallax inc. if you decide to use trademarks of parallax inc. on your web page or in printed material, you must state that ?(trademark) is a tradem ark of parallax inc.?, ?upon the fi rst appearance of the trademark name in each printed document or web page. other brand and product names are trademarks or re gistered trademarks of th eir respective holders. isbn #1-928982-32-8 errata while great effort is made to assure the ac curacy of our texts, errors may still exist. if you find an error, please let us kn ow by sending an email to editor@parallax. com. we continually strive to improv e all of our educational materials and documentation, and frequently revise our texts. occasionally, an errata sheet with a list of known errors and corrections for a given text will be posted to our web site, www.parallax.com. please check the individual product page?s free downloads for an errata file. disclaimer of liability parallax inc. is not responsible for specia l, incidental, or consequential damages re sulting from any breach of warranty, or under any legal theory, including lost pr ofits, downtime, goodwill, damage to or re placement of equipmen t or property, or any costs of recovering, reprogramming, or reproducing any data stored in or used with parallax products. parallax inc. is also not responsible for any personal damage, including that to life and health, resulting from use of any of our products. you take full responsibility for your basic stamp application, no matter how life-threatening it may be. access parallax via internet we maintain very a active web site for your convenience. these may be used to obtain software, communicate with members of parallax, and communicate with other customers. access information is shown below: web: http://www.parallax.com general e-mail: info@parallax.com tech. e-mail: support@parallax.com
internet basic stamp discussion list we maintain active web-based discussion forums for people inte rested in parallax products. these lists are accessible from www.parallax.com via the support discussion forums menu. these are the forums that we operate from our web site: ? basic stamps ? this list is widely utilized by engineers, hobbyists and students who share their basic stamp projects and ask questions. ? stamps in class ? ? created for educators and students, subscribers discuss the use of the stamps in class curriculum in their courses. the list provides an opportunity for both students and educators to ask questions and get answers. ? parallax educators ?exclusively for educators and those who contribute to the development of stamps in class. parallax created this group to obtain f eedback on our curricula and to provide a forum for educators to develop and obtain teacher?s guides. ? translators ? the purpose of this list is to provide a conduit between parallax and those who translate our documentation to languages other than english. parallax provides editable word documents to our translating partners and attempts to time the tr anslations to coordinate wi th our publications. ? robotics ? designed exclusively for parallax robots, this forum is intended to be an open dialogue for a robotics enthusiasts. topics include assembly, source code, expansion, and manual updates. the boe- bot ? , toddler ? , sumobot ? , hexcrawler and quadcrawler robots are discussed here. ? sx microcontrollers and sx-key ? discussion of programming the sx microcontroller with parallax assembly language sx ? key ? tools and 3 rd party basic and c compilers. ? javelin stamp ? discussion of application and design using th e javelin stamp, a parallax module that is programmed using a subset of sun microsystems? java ? programming language. supported hardware, firmware and software this manual is valid with the followi ng software and firmware versions: basic stamp model firmware windows interface basic stamp 1 1.4 2.2 basic stamp 2 1.0 2.2 basic stamp 2e 1.1 2.2 basic stamp 2sx 1.1 2.2 basic stamp 2p 1.4 2.2 basic stamp 2pe 1.1 2.2 basic stamp 2px 1.0 2.2 the information herein will us ually apply to newer versions but may not apply to older versions. new software can be obtained free on web site (www.parallax.com). if you have any questions about what you need to upgrade your product, please contact parallax. credits authorship and editorial review team: jeff martin, jon williams , ken gracey, aristides alvare z, and stephanie lindsay; cover art: jen jacobs; technical graphics, rich allred ; with many thanks to ev eryone at parallax inc.

contents basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 1 preface ...................................................................... 5 introduction to the basic stamp ..................................... 7 basic s tamp m odel c omparison t able .........................................................................8 basic s tamp 1 h ardware .............................................................................................10 basic s tamp 2 h ardware .............................................................................................13 basic s tamp 2 e h ardware ...........................................................................................15 basic s tamp 2 sx h ardware .........................................................................................17 basic s tamp 2 p h ardware ...........................................................................................19 basic s tamp 2 pe h ardware .........................................................................................21 basic s tamp 2 px h ardware .........................................................................................23 g uidelines and p recautions .........................................................................................25 basic s tamp p rogramming c onnections ....................................................................27 quick start guide ....................................................... 29 using the basic stamp editor........................................ 35 t he p rogramming e nvironment ....................................................................................35 c ompiler d irectives ......................................................................................................43 s pecial f unctions .........................................................................................................46 s etting p references ....................................................................................................55 a dvanced c ompilation t echniques ..............................................................................68 f eatures for d evelopers .............................................................................................75 basic stamp architecture............................................ 81 ram o rganization (bs1)...............................................................................................81 ram o rganization (bs2, bs2 e , bs2 sx , bs2 p , bs2 pe ) .................................................82 d efining and u sing v ariables .......................................................................................84 the rules of symbol names ......................................................................................86 defining array variables .............................................................................................87 aliases and variable modifiers ...................................................................................89 c onstants and c ompile - time e xpressions ...................................................................94 n umber r epresentations ..............................................................................................96 o rder of o perations ..................................................................................................102 i nteger m ath r ules .....................................................................................................103 u nary o perators ........................................................................................................105 absolute value (abs) ...............................................................................................105 cosine (cos) ...........................................................................................................106 decoder (dcd) .........................................................................................................106
contents page 2 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com negative (-)...............................................................................................................106 encoder (ncd) .........................................................................................................107 sine (sin) .................................................................................................................107 square root (sqr) ..................................................................................................108 b inary o perators .......................................................................................................109 add (+)......................................................................................................................10 9 subtract (-)................................................................................................................110 multiply (*).................................................................................................................11 0 multiply high (**).......................................................................................................111 multiply middle (*/) ....................................................................................................112 divide (/) ...................................................................................................................11 3 modulus (//)...............................................................................................................113 arctangent (atn)......................................................................................................114 hypotenuse (hyp)....................................................................................................115 minimum (min) .........................................................................................................115 maximum (max).......................................................................................................116 digit (dig).................................................................................................................117 shift left (<<)............................................................................................................117 shift right (>>) .........................................................................................................117 reverse (rev) .........................................................................................................118 and (&) .....................................................................................................................118 or (|) ......................................................................................................................... 118 xor (^).......................................................................................................................1 19 and not (&/)..............................................................................................................120 or not (|/)..................................................................................................................12 0 xor not (^/) ...............................................................................................................121 basic stamp command reference ................................. 123 pbasic l anguage v ersions .......................................................................................123 c ategorical l isting of c ommands .............................................................................124 s yntax c onventions ....................................................................................................128 auxio.......................................................................................................................... .129 branch.......................................................................................................................13 3 button .......................................................................................................................13 7 compare....................................................................................................................141 configpin ..................................................................................................................143 count .........................................................................................................................1 49 data ........................................................................................................................... .153 debug .........................................................................................................................1 59 debugin......................................................................................................................17 1 do...loop....................................................................................................................17 5
contents basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 3 dtmfout.....................................................................................................................179 eeprom.......................................................................................................................18 3 end............................................................................................................................ ...187 exit ........................................................................................................................... ...189 for?next .................................................................................................................191 freqout.....................................................................................................................199 get............................................................................................................................ ...203 gosub .........................................................................................................................2 09 goto........................................................................................................................... .213 high ........................................................................................................................... ..215 i2cin.......................................................................................................................... ...217 i2cout......................................................................................................................... 225 if?then......................................................................................................................23 1 input .......................................................................................................................... .243 ioterm ........................................................................................................................2 47 lcdcmd.......................................................................................................................24 9 lcdin .......................................................................................................................... .257 lcdout .......................................................................................................................26 3 let............................................................................................................................ ....269 lookdown.................................................................................................................271 lookup .......................................................................................................................27 7 low............................................................................................................................ ..281 mainio ......................................................................................................................... 283 nap............................................................................................................................ ...285 on............................................................................................................................. ....289 output .......................................................................................................................29 3 owin ........................................................................................................................... .295 owout ........................................................................................................................30 3 pause.......................................................................................................................... 311 pollin ......................................................................................................................... 313 pollmode ..................................................................................................................319 pollout .....................................................................................................................325 pollrun .....................................................................................................................331 pollwait....................................................................................................................335 pot............................................................................................................................ ...339 pulsin ......................................................................................................................... 343 pulsout .....................................................................................................................347 put............................................................................................................................ ...351 pwm ............................................................................................................................ .355 random ......................................................................................................................359 rctime ........................................................................................................................3 63 read ........................................................................................................................... .369
contents page 4 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com return .......................................................................................................................37 5 reverse.....................................................................................................................377 run ............................................................................................................................ ..381 select...case ...........................................................................................................387 serin .......................................................................................................................... .393 serout .......................................................................................................................41 5 shiftin ........................................................................................................................ 431 shiftout ....................................................................................................................435 sleep .......................................................................................................................... 441 sound .........................................................................................................................4 45 stop ........................................................................................................................... .447 store.......................................................................................................................... 449 toggle .......................................................................................................................45 5 write .......................................................................................................................... 459 xout........................................................................................................................... .465 appendix a: ascii chart .............................................. 471 appendix b: reserved words........................................ 473 appendix c: conversion formatters ............................. 477 appendix d: basic stamp schematics ............................. 481
preface basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 5 thank you for purchasing a parallax basic stamp ? microcontroller module. we have done our best to produce several full-featured, easy to use development systems for basic stamp microcontrollers. depending on the starter kit you purchased, yo ur basic stamp model, development board and other contents will vary. this manual is written for the latest available basic stamp modules and software as of february 2005. as the product-line evolves, new information may become available. it is always recommended to visit the parallax web site, www.parallax.com, for the latest information. this manual is intended to be a complete reference manual to the architecture and command structure of the various basic stamp models. this manual is not meant to teac h basic programming or electrical design; though a person can learn a lo t by paying close attention to the details in this book. if you have never programmed in the basic language or are unfamiliar with electronics, it would be best to locate one or more of the books listed on the following page for assistance. all are available, either to order or to download, from www.parallax.com. books available in adobe?s pdf form at are published for free download on the parallax web site or on the cd-rom which ships with our different starter kits. books available in prin t may be purchased directly from parallax or other distributors. in addition, there are hundreds of grea t examples available on the parallax cd and web site (www.parallax.com ). also, nuts & volts magazine (www.nutsvolts.com / 1-800- 783-4624) is a national electronic hobbyist's magazine that features monthly articles featuring basic stamp applications. this is an excellent reso urce for beginners and experts alike!
preface page 6 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com availability book part # author and publisher pdf in print what?s a microcontroller? 28123 andy lindsay; parallax inc.; isbn 1-928982-02-6 yes yes robotics with the boe-bot 28125 andy lindsay; parallax inc.; isbn 1-928982-03-4 yes yes ir remote for the boe-bot 70016 andy lindsay; parallax inc.; isbn 1-928982-31-x yes yes basic analog and digital 28129 andy lindsay; parallax inc.; isbn 1-928982-04-2 yes yes applied sensors 28127 tracy allen, phd.; parallax inc.; isbn 1- 928982-21-2 yes yes understanding signals 28119 (with full kit) doug pientak; parallax inc.; isbn 1-928982-23-9 yes yes industrial control 27341 marty hebel / will devenport; parallax inc.; isbn 1-928982-08-5 yes yes elements of digital logic 70008 john barrowman; parallax inc.; isbn 1- 928982-20-4 yes yes the microcontroller application cookbook volumes 1 and 2 vol. 1&2: 28113 vol. 2: 28112 matt gilliland; woodglen press; isbn 0-616-11552-7 and 0-972-01590-6 no yes al?s ?world famous? stamp project of the month anthology 70013 al williams; parallax inc.; isbn 1-928982-25-5 portions yes the nuts and volts of basic stamps volumes 1, 2, 3, 4, and 5 vol. 4: 70010 vol. 5: 70015 jon williams, scott edwards and lon glazner; parallax, inc.; isbn 1-928982-10-7, 1-928982-11-5, 1-928982-17-4, 1-928982-24-7 and 1-928982-30-1 yes (all) yes (vol 4 and vol 5) stampworks 27220 jon williams; parallax, inc.; isbn 1-928982-07-7 yes yes stamp 2 communication and control projects 70004 thomas petruzzellis; mcgraw-hill; isbn 0-071411-97-6 no yes programming and customizing the basic stamp computer 27956 scott edwards; mcgraw-hill; isbn 0-071371-92-3 no yes basic stamp 2p 70001 claus kuehnel and klaus zahnert; parallax, inc.; isbn 1-928982-19-0 yes no
1: introduction to the basic stamp basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 7 welcome to the wonderful world of basic stamp ? microntrollers. basic stamp microcontrollers have been in use by engineers and hobbyists since we first introduced them in 1992. as of november 2004, parallax customers have put well over thr ee million basic stamp modules into use. over this 12-year period, the basic stamp line of controllers has evolved into six models and many physical package types, explained below. general operation theory basic stamp modules are microcontrollers (tiny computers) that are designed for use in a wide array of applications. many projects that require an embedded system with some level of intelligence can use a basic stamp module as the controller. each basic stamp comes with a basic interpreter chip, internal memory (ram and eeprom), a 5-volt regulato r, a number of general-purpose i/o pins (ttl-level, 0-5 volts), and a set of built-in commands for math and i/o pin operations. basic stamp mo dules are capable of running a few thousand instructions per second and are programmed with a simplified, but customized form of the basic programming language, called pbasic. pbasic language we developed pbasic specifically for the basic stamp as a simple, easy to learn language that is also well su ited for this architecture, and highly optimized for embedded control. it includes many of the instructions featured in other forms of basic (goto, for...next, if...then?else) as well as some specialized instructions (serin, pwm, button, count and dtmfout). this manual includes an extensive section devoted to each of the available instructions. hardware at the time of this writing, there ar e currently seven models of the basic stamp; the bs1, bs2, bs2e, bs2sx, bs2p, bs2pe, and the bs2px. the tables below are provided to easily compare their specifications, followed by diagrams that detail the various pa ckage types of these modules. schematics for the sip/dip packages of all models can be found in appendix d.
introduction to the basic stamp page 8 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com basic stamp model comparison table products bs1 bs2 bs2e environment 0o - 70o c (32o - 158o f) ** 0o - 70o c (32o - 158o f) ** 0o - 70o c (32o - 158o f) ** microcontroller microchip pic16c56a microchip pic16c57c ubicom sx28ac processor speed 4 mhz 20 mhz 20 mhz program execution speed ~2,000 instructions/sec. ~4,000 instructions/sec ~4,000 instructions/sec ram size 16 bytes (2 i/o, 14 variable) 32 bytes (6 i/o, 26 variable) 32 bytes (6 i/o, 26 variable) scratch padram n/a n/a 64 bytes eeprom (program) size 256 bytes, ~80 instructions 2k bytes, ~500 instructions 8 x 2k bytes, ~4,000 inst number of i/o pins 8 16 + 2 dedicated serial 16 + 2 dedicated serial voltage requirements 5 - 15 vdc 5 - 15 vdc 5 - 12 vdc current draw@ 5 volts 1 ma run, 25 a sleep 3 ma run, 50 a sleep 25 ma run, 200 a sleep source/sink current per i/o 20 ma / 25 ma 20 ma / 25 ma 30 ma / 30 ma source/sink current per unit 40 ma / 50 ma 40 ma / 50 ma per 8 i/o pins 60 ma / 60 ma per 8 i/o pins pbasic commands* 32 42 45 pc interface serial (w/bs1 serial adapter) serial (9600 baud) serial (9600 baud) windows text editor version stampw.exe (v2.1 and up) stampw.exe (v1.04 and up) stampw.exe (v1.096 and up) * pbasic command count totals include pbasic 2.5 commands on all bs2 models. ** see below for industrial rated module information. industrial-rated basic stamp modules some basic stamp models come in industrial-rated versions, with an environmental temperature tolerance range of -40c to +85c . contact the parallax sales team directly for the latest information regarding industrial-rated product availability and specifications.
1: introduction to the basic stamp basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 9 bs2sx bs2p24 bs2p40 bs2pe bs2px 0o - 70o c (32o - 158o f) ** 0o - 70o c (32o - 158o f) ** 0o - 70o c (32o - 158o f) ** 0o - 70o c (32o - 158o f) ** 0o - 70o c (32o - 158o f) ** ubicom sx28ac ubicom sx48ac ubicom sx48ac ubicom sx48ac ubicom sx48ac 50 mhz 20 mhz turbo 20 mhz turbo 8 mhz turbo 32 mhz turbo ~10,000 instructions/sec. ~12,000 instructions/sec. ~12,000 instru ctions/sec. ~6000 instructions/sec. ~19,000 instructions/sec. 32 bytes (6 i/o, 26 variable) 38 bytes (12 i/o, 26 variable) 38 bytes (12 i/o, 26 variable) 38 bytes (12 i/o, 26 variable) 38 bytes (12 i/o, 26 variable) 64 bytes 128 bytes 128 bytes 128 bytes 128 bytes 8 x 2k bytes, ~4,000 inst. 8 x 2k bytes, ~4,000 inst. 8 x 2k bytes, ~4,000 inst. 16 x 2k bytes (16 k for source) 8 x 2k bytes, ~4,000 inst. 16 + 2 dedicated serial 16 + 2 dedicated serial 32 + 2 dedicated serial 16 + 2 d edicated serial 16 + 2 dedicated serial 5 - 12 vdc 5 - 12 vdc 5 - 12 vdc 5 - 12 vdc 5 - 12 vdc 60 ma run, 500 a sleep 40 ma run, 350 a sleep 40 ma run, 350 a sleep 15 ma run, 150 a sleep 55 ma run, 450 a sleep 30 ma / 30 ma 30 ma / 30 ma 30 ma / 30 ma 30 ma / 30 ma 30 ma / 30 ma 60 ma / 60 ma per 8 i/o pins 60 ma / 60 ma per 8 i/o pins 60 ma /60 ma per 8 i/o pins 60 ma / 60 ma per 8 i/o pins 60 ma / 60 ma per 8 i/o pins 45 61 61 61 63 serial (9600 baud) serial (9600 baud) serial (9600 baud) serial (9600 baud) serial (19200 baud) stampw.exe (v1.091 and up) stampw.exe (v1.1 and up) stampw.exe (v1.1 and up) stampw.exe (v1.33 and up) stampw.exe (v2.2 and up) phone: (91 6) 624-8333 toll free in the us or canada: 1-888-512-1024 email: sales@parallax.com
introduction to the basic stamp page 10 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com basic stamp 1 figure 1.1: basic stamp 1 (rev b) (stock# bs1-ic). figure 1.2: basic stamp 1 oem (rev. a) (stock# 27295).
1: introduction to the basic stamp basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 11 figure 1.3: basic stamp 1 (rev dx) (stock# 27100). the basic stamp 1 is available several physical packages. the bs1-ic (figure 1.1) uses surface mount components to fit in a small 14-pin sip package. the preassembled basic stamp 1 oem (figure 1.2) features an easier-to-trace layout meant to aid customers who wish to integrate the basic stamp 1 circuit directly into their design (as a lower-cost solution). the basic stamp 1 rev. dx (simply call ed the rev. dx), see figure 1.3, includes a prototyping area suitable fo r soldering electronic components. these three packages are functionally equivalent, except that the rev. dx does not have an available reset pin. in addition to the packages shown, there are prototyping boards available that feature a surface mounted bs1 and programming cable connector. please check www. parallax.com products
introduction to the basic stamp page 12 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com pin name description 1 vin unregulated power in: accepts 5.5 - 15 vdc (6-40 vdc on bs1-ic rev. b), which is then internally regulated to 5 volts. may be left unconnected if 5 volts is applied to the vdd (+5v) pin. 2 vss system ground: connects to bs1 serial adapter ground for programming. 3 pco pc out: 4800 baud serial output (ttl level) to pc. 4 pci pc in: 4800 baud serial input (ttl level) from pc. 5 vdd 5-volt dc input/output: (also called +5v) if an unregulated voltage is applied to the vin pin, then this pin will output 5 volts. if no voltage is applied to the vin pin, then a regulated voltage between 4.5v and 5.5v should be applied to this pin. 6 res reset input/output: goes low when power supply is less than approximately 4.2 volts, causing the basic stamp to reset. can be driven low to force a reset. th is pin is internally pulled high and may be left disconnected if not needed. do not drive high. 7-14 p0-p7 general-purpose i/o pins: each can sink 25 ma and source 20 ma. however, the total of all pins should not exceed 50 ma (sink) and 40 ma (source). table 1.1: basic stamp 1 pin descriptions. see the "basic stamp programming connections" section on page 27 for more information on the required programming connections between the pc and the basic stamp.
1: introduction to the basic stamp basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 13 basic stamp 2 figure 1.4: basic stamp 2 (rev. g) (stock# bs2-ic). figure 1.5: basic stamp 2 oem (rev. a2) (stock# 27290 assembled, or #27291 in kit form). the basic stamp 2 is available in several physical packages. the bs2-ic (figure 1.4) uses surface mount components to fit in a small 24-pin dip package. the basic stamp 2 oem (figure 1.5) features an easier-to-trace layout meant to aid customers who wish to integrate the basic stamp 2 circuit directly into their design (a s a lower-cost solution). the basic
introduction to the basic stamp page 14 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com stamp 2 oem is available in either an assembled form or a kit form. these three packages are functionally equivalent. in addition to the dual-inline and oem packages, there are prototyping boards available that feature a surface mounted bs2. please check www.parallax.com products
1: introduction to the basic stamp basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 15 basic stamp 2e figure 1.6: basic stamp 2e (rev. b) (stock# bs2e-ic). the basic stamp 2e is available in the above 24-pin dip package. table 1.3: basic stamp 2e pin descriptions. pin name description 1 sout serial out: connects to pc seri al port rx pin (db9 pin 2 / db25 pin 3) for programming. 2 sin serial in: connects to pc serial port tx pin (db9 pin 3 / db25 pin 2) for programming. 3 atn attention: connects to pc serial port dtr pin (db9 pin 4 / db25 pin 20) for programming. 4 vss system ground: (same as pin 23) connects to pc serial port gnd pin (db9 pin 5 / db25 pin 7) for programming. 5-20 p0-p15 general-purpose i/o pins: each can source and sink 30 ma. however, the total of all pins sh ould not exceed 75 ma (source or sink) if using the internal 5-volt regulator. the total per 8-pin groups (p0 ? p7 or p8 ? 15) should not exceed 100 ma (source or sink) if using an external 5-volt regulator. 21 vdd 5-volt dc input/output: if an unregulated voltage is applied to the vin pin, then this pin will output 5 volts. if no voltage is applied to the vin pin, then a regulated voltage between 4.5v and 5.5v should be applied to this pin. 22 res reset input/output: goes low when power supply is less than approximately 4.2 volts, causing the basic stamp to reset. can be driven low to force a reset. th is pin is internally pulled high and may be left disconnected if not needed. do not drive high. 23 vss system ground: (same as pin 4) connects to power supply?s ground (gnd) terminal. 24 vin unregulated power in: accepts 5.5 - 12 vdc (7.5 recommended), which is then internally regulated to 5 volts. must be left unconnected if 5 volts is applied to the vdd (+5v) pin.
introduction to the basic stamp page 16 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com see the "basic stamp programming connections" section on page 27 for more information on the required programming connections between the pc and the basic stamp.
1: introduction to the basic stamp basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 17 basic stamp 2sx figure 1.7: basic stamp 2sx (rev. e) (stock# bs2sx-ic) figure 1.8: basic stamp 2sx oem (rev. a2) (stock# 27294) the basic stamp 2sx is available in the above two physical packages. the bs2sx-ic (figure 1.7) uses surfac e mount components to fit in a small 24-pin dip package. the preassembled basic stamp 2sx oem (figure 1.8) features an easier-to-trace layout meant to aid customers who wish to integrate the basic stamp 2sx circuit directly into their design (as a lower-cost solution). the basic stamp 2sx oem is available in assembled form only.
introduction to the basic stamp page 18 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com pin name description 1 sout serial out: connects to pc seri al port rx pin (db9 pin 2 / db25 pin 3) for programming. 2 sin serial in: connects to pc serial port tx pin (db9 pin 3 / db25 pin 2) for programming. 3 atn attention: connects to pc serial port dtr pin (db9 pin 4 / db25 pin 20) for programming. 4 vss system ground: (same as pin 23) connects to pc serial port gnd pin (db9 pin 5 / db25 pin 7) for programming. 5-20 p0-p15 general-purpose i/o pins: each can source and sink 30 ma. however, the total of all pins should not exceed 75 ma (source or sink) if using the internal 5-vo lt regulator. the total per 8-pin groups (p0 ? p7 or p8 ? 15) should not exceed 100 ma (source or sink) if using an external 5-volt regulator. 21 vdd 5-volt dc input/output: if an unregulated voltage is applied to the vin pin, then this pin will output 5 volts. if no voltage is applied to the vin pin, then a regulated voltage between 4.5v and 5.5v should be applied to this pin. 22 res reset input/output: goes low when power supply is less than approximately 4.2 volts, causing the basic stamp to reset. can be driven low to force a reset. this pin is internally pulled high and may be left disconnected if not needed. do not drive high. 23 vss system ground: (same as pin 4) connects to power supply?s ground (gnd) terminal. 24 vin unregulated power in: accepts 5.5 - 12 vdc (7.5 recommended), which is then internally regulated to 5 volts. must be left unconnected if 5 volts is applied to the vdd (+5v) pin. table 1.4: basic stamp 2sx pin descriptions see the "basic stamp programming connections" section on page 27 for more information on the required programming connections between the pc and the basic stamp.
1: introduction to the basic stamp basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 19 basic stamp 2p figure 1.9: basic stamp 2p24 (rev. c) (stock# bs2p24-ic) this module is identical in function to the bs2p40-ic, except that it has 16 i/o pins. figure 1.10: basic stamp 2p40 (rev. b) (stock# bs2p40-ic) this module is identical in function to the bs2p24-ic, except that it has 32 i/o pins. the basic stamp 2p is available in the above two physical packages. both packages use surface mount components to fit in a small package. the bs2p24-ic (figure 1.9) is a 24-pin dip package. the bs2p40-ic (figure 1.10) is a 40-pin dip package. both packages are functionally equivalent accept that the bs2p40 has 32 i/o pins instead of 16.
introduction to the basic stamp page 20 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com pin name description 1 sout serial out: connects to pc seri al port rx pin (db9 pin 2 / db25 pin 3) for programming. 2 sin serial in: connects to pc serial port tx pin (db9 pin 3 / db25 pin 2) for programming. 3 atn attention: connects to pc serial port dtr pin (db9 pin 4 / db25 pin 20) for programming. 4 vss system ground: (same as pin 23 on bs2p24, or pin 39 on bs2p40) connects to pc serial port gnd pin (db9 pin 5 / db25 pin 7) for programming. 5-20 p0-p15 general-purpose i/o pins: each can source and sink 30 ma. however, the total of all pins (including x0-x15, if using the bs2p40) should not exceed 75 ma (s ource or sink) if using the internal 5-volt regulator. the total per 8-pin groups (p0 ? p7, p8 ? 15, x0 ? x7 or x8 ? x15) should not exceed 100 ma (source o r sink) if using an exter nal 5-volt regulator. {21-36} x0-x15 (bs2p40 only!) auxiliary bank of general-purpose i/o pins: each can source and sink 30 ma. however, the total of all pins (including p0 ? p15) should not ex ceed 75 ma (source or sink) if using the internal 5-volt regulator . the total per 8-pin groups (p0 ? p7, p8 ? 15, x0 ? x7 or x8 ? x15) should not exceed 100 ma (source or sink) if using an external 5-volt regulator. 21 {37} vdd 5-volt dc input/output: if an unregulated voltage is applied to the vin pin, then this pin will output 5 volts. if no voltage is applied to the vin pin, then a regulated voltage between 4.5v and 5.5v should be applied to this pin. 22 {38} res reset input/output: goes low when power supply is less than approximately 4.2 volts, causing the basic stamp to reset. can be driven low to force a reset. th is pin is internally pulled high and may be left disconnected if not needed. do not drive high. 23 {39} vss system ground: (same as pin 4) connects to power supply?s ground (gnd) terminal. 24 {40} vin unregulated power in: accepts 5.5 - 12 vdc (7.5 recommended), which is then internally regulated to 5 volts. must be left unconnected if 5 volts is applied to the vdd (+5v) pin. table 1.5: basic stamp 2p pin connections see the "basic stamp programming connections" section on page 27 for more information on the required programming connections between the pc and the basic stamp.
1: introduction to the basic stamp basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 21 basic stamp 2pe figure 1.11: basic stamp 2pe (rev. b) (stock# bs2pe-ic) the basic stamp 2pe is available in the above 24-pin dip physical package. table 1.6: basic stamp 2pe pin descriptions. pin name description 1 sout serial out: connects to pc serial port rx pin (db9 pin 2 / db25 pin 3) for programming. 2 sin serial in: connects to pc serial po rt tx pin (db9 pin 3 / db25 pin 2) for programming. 3 atn attention: connects to pc serial port dtr pin (db9 pin 4 / db25 pin 20) for programming. 4 vss system ground: (same as pin 23), c onnects to pc serial port gnd pin (db9 pin 5 / db25 pin 7) for programming. 5-20 p0-p15 general-purpose i/o pins: each can source and sink 30 ma. however, the total of all pins sh ould not exceed 75 ma (source or sink) if using the internal 5-volt re gulator. the total per 8-pin groups p0 ? p7 or p8 ? 15 should not ex ceed 100 ma (source or sink) if using an external 5-volt regulator. 21 vdd 5-volt dc input/output: if an unregulated voltage is applied to the vin pin, then this pin will output 5 volts. if no voltage is applied to the vin pin, then a regulated voltage between 4.5v and 5.5v should be applied to this pin. 22 res reset input/output: goes low when power supply is less than approximately 4.2 volts, causing the basic stamp to reset. can be driven low to force a reset. this pin is internally pulled high and may be left disconnected if not needed. do not drive high. 23 vss system ground: (same as pin 4) connects to power supply?s ground (gnd) terminal. 24 vin unregulated power in: accepts 5.5 - 12 vdc (7.5 recommended), which is then internally regulated to 5 volts. must be left unconnected if 5 volts is applied to the vdd (+5v) pin.
introduction to the basic stamp page 22 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com see the "basic stamp programming connections" section on page 27 for more information on the required programming connections between the pc and the basic stamp.
1: introduction to the basic stamp basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 23 basic stamp 2px figure 1.12: basic stamp 2px (rev. a) (stock# bs2px -ic) the basic stamp 2px is available in the above 24-pin dip physical package. table 1.7: basic stamp 2px pin descriptions. pin name description 1 sout serial out: connects to pc serial port rx pin (db9 pin 2 / db25 pin 3) for programming. 2 sin serial in: connects to pc serial po rt tx pin (db9 pin 3 / db25 pin 2) for programming. 3 atn attention: connects to pc serial port dtr pin (db9 pin 4 / db25 pin 20) for programming. 4 vss system ground: (same as pin 23), c onnects to pc serial port gnd pin (db9 pin 5 / db25 pin 7) for programming. 5-20 p0-p15 general-purpose i/o pins: each can source and sink 30 ma. however, the total of all pins sh ould not exceed 75 ma (source or sink) if using the internal 5-volt re gulator. the total per 8-pin groups p0 ? p7 or p8 ? 15 should not ex ceed 100 ma (source or sink) if using an external 5-volt regulator. 21 vdd 5-volt dc input/output: if an unregulated voltage is applied to the vin pin, then this pin will output 5 volts. if no voltage is applied to the vin pin, then a regulated voltage between 4.5v and 5.5v should be applied to this pin. 22 res reset input/output: goes low when power supply is less than approximately 4.2 volts, causing the basic stamp to reset. can be driven low to force a reset. this pin is internally pulled high and may be left disconnected if not needed. do not drive high. 23 vss system ground: (same as pin 4) connects to power supply?s ground (gnd) terminal. 24 vin unregulated power in: accepts 5.5 - 12 vdc (7.5 recommended), which is then internally regulated to 5 volts. must be left unconnected if 5 volts is applied to the vdd (+5v) pin.
introduction to the basic stamp page 24 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com see the "basic stamp programming connections" section on page 27 for more information on the required programming connections between the pc and the basic stamp.
1: introduction to the basic stamp basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 25 guidelines and precautions when using the basic stamp, or any ic chip, please follow the guidelines below. 1. be alert to static sensitive devices and static-prone situations. a. the basic stamp, like other ic?s, can be damaged by static discharge that commonly occurs touching grounded surfaces or other conductors. environmental conditions (humidity changes, wind, static prone surfaces, etc) play a major role in the presence of random static charges. it is always recommended to use grounding straps and anti-static or static dissipative mats when handling devices like the basic stamp. if the items above are not available, be sure to touch a grounded surface after you have approached the work area and before you handle static sensitive devices. 2. verify that all power is off before connecting/disconnecting. a. if power is connected to the basic stamp or any device it is connected to while inserting or removing it from a circuit, damage to the ba sic stamp or circuit could result. 3. verify basic stamp orientat ion before connection to development boards and other circuits. a. like other ic?s, the basic stamp should be inserted in a specific orientation in relation to the development board or circuit. powering the ci rcuit with an ic connected backwards will likely damage the ic and/or other components in the circuit. most ic?s have some form of a ?pin 1 indicator? as do most ic sockets. this indicator usually takes the form of a dot, a half-circle, or the number 1 placed at or near pin 1 of the device. the bs1-ic has a ?1? and a half-circle indicator on the backside of the module. a dditionally, figure 1.1 above indicates the pin numbering and labels. all bs2 series modules have a half-circle indicator on the topside of the module (see figure 1.13). this indicates that pin number one is the first pin counterclockwise from the notch. the socket that a ccepts this 24-pin module also
introduction to the basic stamp page 26 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com has a half-circle or notch on one end, indicating the correct orientation. see figure 1.14 for other examples. rev g 24 23 22 21 20 19 16 15 14 18 17 13 1 2 3 4 5 6 9 10 11 7 8 12 figure 1.13: pin 1 indicators bs2-ic shown in the correct orientation in relation to a 24-pin socket. note: the half-circle indicator is also known as a reference notch figure 1.14: additional examples of pin 1 indicators (chip and socket shown in the correct orientation in relation to each other) ?dot? (pin 1 indicator) ?1? printed on pc board (pin 1 indicator) insert pin 1 here 1 reference notch pin 1 ( pin 1 indicator ) insert pin 1 reference here notch
1: introduction to the basic stamp basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 27 basic stamp programming connections we suggest using a parallax development board and cable for programming basic stamp modules. wh en these items are not available, you may create your own board by duplicating the following diagrams with your own circuits and cables. be very careful to follow these diag rams closely; it is quite common for programming problems with the basic stamp to be a result of a poorly made custom cable or programming connections on your applications board. with the programming connections for all the bs2 models, it is possible to reverse a couple of wires and still get positive results using some of the "connection" tests our tech. support team tries and yet you still will not be able to communicate with the basic stamp. it is vital that you check your connections with a meter and verify the pin numbering to avoid problems like this. figure 1.15: bs1 programming connections with bs1 serial adapter note: though it is not shown, power must be connected to the bs1 to program it.
introduction to the basic stamp page 28 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com figure 1.16: programming and run-time communication connections for all bs2 models. note: though it is not shown, power must be connected to the basic stamp to program it. also, the programming connections are the same for the bs2p40.
2: quick start guide basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 29 quick start introduction this chapter is a quick start guide to connecting the basic stamp to the pc and programming it. without even knowing how the basic stamp functions, you should be able to complete the exercise below. this exercise assumes you have a basic stamp and an appropriate development board. for the latest parallax development board selection and documentation, go to www.parallax.com development boards. for a more detailed introduction to the basic stamp editor software, see chapter 3. equipment needed ? basic stamp module ? compatible carrier board and programming cable ? power supply (wall mount or battery) rated for your carrier board ? pc running windows ? 2000/xp, with o quantity of ram recommended for the os o 3 mb of hard drive space o cd-rom drive or internet access o available port compatible with your carrier board and cable (serial or usb) connecting and downloading 1) if the basic stamp isn't already plugged into your development board, insert it into the socket. refer to figure 1.13 and figure 1.14 on page 26 to make sure that you orient it correctly. for a complete listing of parallax development boards for the various basic stamp modules, go to www.parallax.com and look for development boards on the products menu. 2) if you are using a parallax development board, follow the directions that came with it to connect the bo ard to the appropriate port in your computer. figure 2.1 below shows the proper sequence for setting up with a bs1 and a bs1 carrier board. figure 2.2 on page 31 shows the proper sequence to connect any bs2. note: if you are using your own
quick start guide page 30 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com development board or a breadboard, carefully follow the programming connections guidelines on page 27 before proceeding. figure 2.1: bs1-ic, bs1 carrier board, and bs1 serial adapter 1) insert the basic stamp module into its socket, being careful to orient it properly. 2) connect the 9-pin female end of the serial cable to an available serial port on your computer, then attach the male end to the bs1 serial adapter, note: you cannot us a null modem cable. 3) plug the bs1 serial adapter into the programming header on the bs1 carrier board. 4) plug a 9 volt battery into the 9 vdc battery clip.
2: quick start guide basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 31 figure 2.2: bs2-ic and board of education 1) insert the basic stamp module into its socket, being careful to orient it properly. 2) connect the 9-pin female end of the serial cable to an available serial port on your computer, and then connect the male end to the board of education. note: you cannot use a null modem cable. 3) plug in the 6-9 v 300ma center- positive power supply into the barrel jack. or 4) plug a 9 volt battery into the 9 vdc battery clip. a l k a l i n e b a t t e r y p o w e r c e l l 2 1 www.stampsinclass.com reset s t a m p s c l a s s i n board of education pwr 9 vdc battery 6-9vdc sout sin atn vss p0 p1 p2 p3 p4 p5 p6 p7 p11 p9 p8 vin p10 p15 p14 p13 p12 vdd rst vss black red x4 x5 15 14 13 12 1 x1 vss p1 p3 p5 p7 p9 p11 p13 p15 vin vss p0 p2 p4 p6 p8 p10 p12 p14 vdd u1 tm 0 1 2 ? 2000-2003 vdd p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0 x2 x3 vdd vss vin 3 4 or 3) install and run the basic stamp editor software. a) if using the parallax cd, go to the software if using the parallax websit e, go to www.parallax.com test your pc?s connection to th e basic stamp by selecting run
quick start guide page 32 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com select run identify verify that the basic stamp was detected on one of the com ports. figure 2.3: test your pc connection to the basic stamp. 4) enter a $stamp directive into the editor window by clicking on the toolbar icon for the basic stamp module you are using. (hold the cursor over the icons for flyover help labels.) the example below shows the stamp directive that wo uld be inserted for the bs2. ' {$stamp bs2} 5) enter a $pbasic directive into the editor window with the toolbar icon. for a bs1, you must use pbasic 1.0. all bs2 series modules can use pbasic 2.0 or 2.5. the command set differences between pbasic 2.0 and 2.5 are covered in chapter 5. click on the icon that corresponds to your basic stamp model to automatically place the $stamp directive in your program. click on the icon for the pbasic language version that is compatible with your basic stamp model. figure 2.4: entering the $stamp and $pbasic directives from the toolbar the examples shown would be used for programming a bs2 module in pbasic 2.5 you should now see both a $stamp directive and $pbasic directive on your pc screen: ' {$stamp bs2} ' {$pbasic 2.5} a) note: these directives may be typed in from the keyboard, but failure to type this line properly may cause the editor to fail to recognize your basic stamp during the next step.
2: quick start guide basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 33 6) type the line debug ?hello world!? below the compiler directives: ' {$stamp bs2} ' {$pbasic 2.5} debug "hello world!" 7) download this program into the basic stamp. you may select run ? to run your program, you may use the task bar menu or the run icon. selecting run : run using the run toolbar icon a) if the program is typed correctly , a progress bar window should appear (perhaps very briefly) showing the download progress. then a debug terminal window should appear and display "hello world!" figure 2.6: debug terminal displaying program output b) if there is a syntax error in the program, the editor will highlight the text in question and display an error message. review the error, fix the code and then try downloading again.
quick start guide page 34 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com c) if the error reported a connection problem with the basic stamp, make sure the first line of code indicates the proper module name and verify the programming cable connections, module orientation (in the socket) and that it is properly powered, then try downloading again. 8) congratulations! you've just wr itten and downloaded your first basic stamp program! the "hello world!" text that appeared on the screen was sent from the basic stamp, back up the programming cable, to the pc.
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 35 introducing the basic stamp editor this section describes the basic stamp editor for windows version 2.2. this software supports all 7 basi c stamp modules available as of february 2005, and all 3 versions of the pbasic programming language, pbasic 1.0, pbasic 2.0, and pbasic 2.5. the programming environment the basic stamp windows editor, shown in figure 3.1, was designed to be easy to use and mostly intuitive. those that are familiar with standard windows software should feel comfortable using the basic stamp windows editor. figure 3.1: basic stamp windows editor. the editor window consists of the main edit pane with an integrated explorer panel to its left, as shown above. the main edit pane can be used to view and modify up to 16 different source code files at once. each source code file that is loaded into the t he editor window . t he main edit pane .
using the basic stamp editor page 36 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com editor will have its own tab at the top of the page labeled with the name of the file, as seen in figure 3.2. the full file path of the currently displayed source code appears in the title bar. source code that ha s never been saved to disk will default to ?untitled#?; where # is an automatically generated number. a user can switch between source code files by simply pointing and clicking on a file?s tab or by pre ssing ctrl+tab or ctrl+shift+tab while the main edit pane is active. figure 3.2: example editor tabs. shown with 6 separate files open; title bar shows current code?s file path. the status of the active source code is indicated in the status bar below the main edit pane and integrated explorer panel. the status bar contains information such as cursor position, fi le save status, download status and syntax error/download messages. the example in figure 3.3 indicates that the source code tokenized successfully. figure 3.3: status bar beneath the main edit pane. each editor pane can be individually split into two views of the same source code. this can be done via the split button on the toolbar, pressing ctrl-l, or clicking and dragging the top or bottom border of the editor pane with the mouse. once split, the top and bottom edit co ntrols allow viewing of different areas of the same source code; this can be handy when needing to keep variable declarations or a particular routine in view while modifying a related section of code elsewhere. no te that the split button and ctrl+l shortcut act like a toggle function, sp litting or un-splitting the edit pane. s plit w indow v iew .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 37 figure 3.4: the split edit pane feature displaying the beginning and end of a long program at the same time. within the edit pane, basic stamp so urce code files are displayed with syntax highlighting. syntax highligh ting applies designated colors and character case (upper, lower, capitalized) to reserved words in the pbasic language . this happens automatically as you type. table 3.1 shows the default syntax highlighting setti ngs for each syntax element. if you copy and paste a program into a blank edit pane, select run
using the basic stamp editor page 38 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com syntax element text color character case command blue upper case comment green no change constant -binary default no change constant - decimal default no change constant - hexadecimal default no change constant ? predefined purple upper case constant ? string red no change operators default upper case declaration default upper case directive, conditional comp ile gray(bold) upper case directive, editor teal (bold) upper case directive, target module teal (bold) upper case input/output formatter navy upper case selection white on navy no change search match lime on black no change variable modifier default upper case variable ? predefined purple upper case variable, type default capitalize table 3.1: syntax highlighting defaults for the pbasic scheme. note: the default edit pane has a white background with black characters. automatic line numbers can be enable d or disabled via the ?show line numbers? checkbox on the preferences figure 3.5: automatic line numbering appears in the gutter to the left of the edit pane. yellow bookmarks are visible on lines 5 and 9. bookmarks can be enabled or disa bled via the ?show bookmarks? checkbox on the preferences
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 39 bookmark from either the edit menu or from the shortcut menu (right- click) in the edit pane. you can navigate through and edit your code in the edit pane with keyboard shortcuts, most of which will be familiar to windows users. table 3.2: keyboard shortcuts for editing and navigation functions. editing and navigation functions shortcut key function ctrl+a select all text in current source code ctrl+b set or clear bookmark on current source code line ctrl+(#) go to bookmark #, where # can be 1 through 9 ctrl+c copy selected text to the clipboard ctrl+f find or replace text ctrl+l split or un-split edit pane ctrl+n insert line ctrl+v paste text from clipboard to selected area ctrl+x cut selected text to the clipboard ctrl+y delete current line of code ctrl+shift+y delete from cursor to end of current line ctrl+z undo last action (unlimited) ctrl+shift+z redo last action (unlimited) tab indent block (inserts tab or space characters) shift+tab outdent block (delet es tab or space characters) f3 find text again f4 replace current found selection ctrl+f4 perform replace and find next ctrl+home jump to top of file ctrl+end jump to end of file ctrl+pageup jump to top of screen ctrl+pagedown jump to bottom of screen ctrl+cursorup move source view up one line without moving cursor ctrl+cursordown move source view down one line without moving cursor f5 open preferences window some editing functions, specifically cut, copy, paste, and find/replace, can also be accessed from the edit pane?s shortcut menu (by right-clicking in the edit pane). the find/replace window allows you to set several search parameters. match whole or partial words, match case, and match with wildcard options can be used singly or togeth er. you can begin your search at the cursor or at the top or bottom of the se lection or the entire file, and search in the forward (downward) or backward (upward) direction. you may replace a single instance of a given item or all instances at once. recent t he f ind /r eplace w indow . e diting your code .
using the basic stamp editor page 40 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com find and replace items are saved in the find: and replace: field?s drop- down lists. figure 3.6: the find/replace window. the find/replace window will stay vi sible when using the find next and replace options for quick and convenient source code editing. using the replace all function, however, will close the find/replace window and perform the designated find/replace operation. the integrated explorer panel to the le ft of the main edit pane is divided in to four portions: the recent, directory, file and filter lists. the upper portion is the recent list, a drop-down li st of default, favorite, and recently visited directories. if you select a directory from the recent list drop down field, the integrated explorer will automaticall y navigate to that directory. the button to the left of the recent list al lows you to limit the directory list display below it to only the directorie s that are in the recent list. this makes it easy to find your commonly used source code directories among a large set of directories and local an d network hard drives. the recent list button behaves like a toggle switch : 1) selecting it switches to the ?show recent folders only? mode, 2) selecting it again switches back to the ?show all folders? mode. t he i ntegrated e xplorer p anel .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 41 figure 3.7: the integrated explorer panel?s recent list (top), directory list (middle), and file list (bottom). the directory list, right below the recent list, displays drives and directories in a hierarchical tree fashion. if a directory is selected, the folders list displays the files in that directory. the file list, below the directory list, displays all the files in the selected directory that match the selected filter (from the filter list at the bottom. see figure 3.8). you can select one or more files from this list and double- click, or drag-and-drop them over the editor pane, to open those files. you may also open files with the op en from... option by selecting file
using the basic stamp editor page 42 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com figure 3.8: the filter list found at the bottom of the integrated explorer panel. the basic stamp editor automatically associates basic stamp source code file types (.bs1, .bs2, .bse, .bsx, .bsp, .bpe, and .bpx) with itself. this feature can be configured through automatic prompts or through the preferences file functions shortcut key function ctrl+e show/hide explorer panel ctrl+l show/hide split view in edit pane ctrl+o open a source code file into edit pane ctrl+shift+o open a source code file fr om a recent directory into edit pane ctrl+s save current source code file to its current location on disk ctrl+shift+s save current source code file to a recent directory on disk ctrl+p print current source code ctrl+tab switch to next open file page ctrl+shift+tab switch to previous open file page table 3.3: keyboard shortcuts for file functions. .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 43 compiler directives the basic stamp editor supports all of the basic stamp models, and all versions of the pbasic programming language. compiler directives must be placed in each program to indicate the desired basic stamp model and language version. in addition, it is sometimes useful to target a given program to a particular communication port. the directive menu contains options for setting the $stamp, $pba sic, and $port directives. since the $stamp and $pbasic directives are used most often, they are most easily inserted or modified with th e toolbar buttons, as shown in figure 3.9. figure 3.9: toolbar icons make it easy to insert or modify $stamp and $pbasic directives directly in your program. a $stamp directive is required in each pbasic program. the editor determines which basic stamp model to target for compiling and downloading based on this directive. any code that is missing the $stamp directive, but whose filena me contains a known basic stamp extension (.bs1, .bs2, .bse, .bsx, .bsp, .b pe, .bpx) will be recognized by that extension and an appropriate $stamp directive will be added automatically when you run, tokenize, view the memory map or download the program. if there is no file extension present, an error message will prompt you to enter a $stamp directive. you may choose to manually type the $stamp directive into the program from the keyboard. this line should be entered into your code on a line by itself, usually near the top. note that the directive appears on a comment line, as indicated by the apostrophe ('). ' {$stamp bs1} 'this indicates to use a basic stamp 1 module ' {$stamp bs2} 'this indicates to use a basic stamp 2 module ' {$stamp bs2e} 'this indicates to use a basic stamp 2e module ' {$stamp bs2sx} 'this indicates to use a basic stamp 2sx module ' {$stamp bs2p} 'this indicates to use a basic stamp 2p module ' {$stamp bs2pe} 'this indicates to use a basic stamp 2pe module ' {$stamp bs2px} 'this indicates to use a basic stamp 2px module c ompiler d irectives . f ormat of the $stamp directive . the $stamp directive .
using the basic stamp editor page 44 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com if you choose to type the $stamp directive, care must be taken, or it will not be recognized. the directive itself must be enclosed in curly braces, {?}, not parentheses (...) or square brackets [...]. there should not be any spaces between the dollar sign ($) and the word stamp; however, the directive may contain additional spaces in certain other areas. for example: ' { $stamp bs2 } -- or -- ' {$stamp bs2} -- and -- ' {$stamp bs2 } are all acceptable variations. however: ' {$ stamp bs2} -- and -- ' {$stampbs2} are not acceptable and will be ignored. if one of the above two lines were entered into the source code, the editor would ignore it and, instead, rely on the extension of the filename to determine the appropriate model. the $stamp directive is read and acted upon by the basic stamp windows editor any time a source code file is loaded, tokenized, downloaded (run) or viewed in the memory map. in some cases you may wish to write a program that can run on multiple basic stamp models. in this case, co nditional compile directives can be employed that will cause the editor to determine which basic stamp model is detected, and then download only those program elements applicable to that model. many of the demo programs in chapter 5 use this technique. to read about cond itional compilation, see the advanced compilation techniques section which begins on page 68. the $pbasic directive allows you to indicate which version of the pbasic language to use. at the time of this printing, the options are 1.0, 2.0 and 2.5. if no $pbasic directive is present in the program, version 1.0 is assumed for bs1 module source code, and version 2.0 is assumed for e xtra spaces are allowed in certain areas . t he $pbasic d irective . p rograms for m ultiple basic s tamp m odels ? c onditional c ompile .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 45 any bs2 model source code. a $pbasic directive is required to use version 2.5, which is compatible with all bs2 models. pbasic 2.5 has enhanced syntax options for several commands, as well as some additional commands not available in pbasic 2.0. table 3.4 shows the number of pbasic commands that ar e available in each version of the pbasic language, on each basic stamp model. details about the syntax differences among the three versions of pbasic are denoted by icons in the margins of chapters 4 and 5; also refer to table 5.1 on page 124 and individual command syntax descriptions. table 3.4: number of available commands for each basic stamp model with each version of the pbasic language . bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px pbasic 1.0 32 - - - - - - pbasic 2.0 - 37 40 40 56 56 58 pbasic 2.5 - 42 45 45 61 61 63 a categorical listing of all pbasic commands is included at the beginning of chapter 5, followed by detailed descriptions of each command in alphabetical order. note that the syntax-highlighting fe ature of the basic stamp editor will also adjust to the language version indicated by the $pbasic directive. the best way to select the $pbasic dire ctive is to use the toolbar icons, as was shown in figure 3.9. like the $stamp directive, you must use care if you choose to type it in by hand. the syntax is: ' {$pbasic 1.0} 'default when a basic stamp 1 module is detected ' {$pbasic 2.0} 'default when any basic stamp 2 module is detected ' {$pbasic 2.5} 'required for pbasic 2.5 command set & enhanced syntax if you try to run a program that contains command syntax specific to pbasic 2.5 without including the corresponding compiler directive, you will probably get an error message. in this case, insert a $pbasic 2.5 directive and try running the program again. the optional $port directive allows you to indicate a specific pc communications port through which to download a program to a basic stamp module. the syntax is as follows: ' {$port com#} where # is a valid port number. when any pbasic program containing this directive is downloaded, all other po rts will be ignored. this directive is especially convenient when using two of the same basic stamp models t he $port d irective .
using the basic stamp editor page 46 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com (such as two bs2s) on two ports and you have two different pbasic programs to download (one to ea ch bs2). without this directive, developing and downloading in this case would be a tedious task of always answering the "which basic stamp?" prompt. the $port directive can be automati cally inserted or modified by selecting the appropriate port from the directive special functions the identify function will identify which basic stamp model, if any, is detected on any available communica tions port. this information is displayed in the identification window (figure 3.10), which can greatly aid in troubleshooting your connection to your basic stamp module. activate this function by selecting run figure 3.10: the identification window. the port column shows the available ports (those that the basic stamp editor is trying to access). you can modify the available port list by clicking on the edit port list button. modifying this list only affects which ports the basic stamp editor tries to us e; it does not affect which serial ports are installed on your computer. it is recommended that you delete all known modem ports and any problematic ports from this list. the i dentification f unction .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 47 the device type column shows the model of basic stamp found on the respective port. for example, in figure 3.10 above, the basic stamp editor found a bs2 on com port 1 and a bs2sx on com port 4. the version column displays the firmware version number of the basic stamp module that was found. the loopback column indicates whethe r or not a loopback connection was found on the port. the loopback connection is created by basic stamp development boards, such as the board of education, across serial port pins 6 and 7 (of a db9). a ?yes? in this column is an indication that the serial port and serial cable are properly connected to a basic stamp development board. note that the loopback column should always indicate ?no? when using a bs1 serial adapter, regardless of whether or not the adapter is properly connect ed to a basic stamp development board. the echo column indicates whether or not a communication echo was detected on the port?s transmit and receive pins (pins 2 and 3). all basic stamp 2 models create this echo natu rally, even without power. basic stamp 1 modules do not create this echo. a ?yes? in this column is an indication that the serial port and serial cable are properly connected to a basic stamp 2 (or higher) module, and if using a basic stamp development board, it?s an indication that the module is properly connected to the development board. for all basic stamp 2 models, the loopback and echo columns are great for doing some simple connection diagnosis when using a serial port. for example, a yes in both columns indicates the serial port and serial cable are properly connected and that the basic stamp is properly inserted into its socket. see table 3.5 below. note that the loopback column does not give reliable results when using a usb to serial adapter, or a usb-based development board. usually this is not an error, and the loopback status can simply be ignored. note: when using a bs1 serial adapter, the loopback column of the identification window should always indicate ?no?.
using the basic stamp editor page 48 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com loopback echo interpretation yes yes serial port and serial cable properly connected. basic stamp properly inserted into socket. if no basic stamp is detected, it is probably because the basic stamp is not connected to power. other causes could be: 1) low battery, 2) reset pin of basic stamp is connected to vdd (it should be left disconnected), 3) the basic stamp is damaged or 4) there is some other type of communication error (software or hardware). yes no serial port and serial cable prope rly connected to the development board. basic stamp improperly inserted into socket (i.e.: inserted backwards or not inserted at all). no yes serial port and serial cable may be improperly connected, or you may not be using a standard basic stamp development board. the echo indicates there may be a basic stamp properly connected to the port (the loopback is not required for successful connection) or there may be another device connected to the serial port. no no serial port and serial cable are not properly connected, or not connected at all, to the basic stamp 2 (and higher) modules. could also be an indication of a serial port hardware/software problem. when using a bs1 serial adapter, this loopback and echo is normal and expected. table 3.5: using loopback and echo to troubleshoot your serial port (db9) connection. note: when using a usb port, the loopback column does not give reliable results. usually this is not an error and the loopback status can be ignored. selecting the ?ignore bs1 modules unless downloading bs1 source code? checkbox at the bottom of the identification window optimizes identification speed. all bs2 models can be identified very quickly. for basic stamp 1 modules, the identification process can take as much as five seconds per communications port. since the identification function checks all available serial ports for any possible model of basic stamp, the five-second timeout for bs1?s can be very inconvenient, especially if you are not using a bs1. when this checkbox is checked, the identification function will not attempt to locate bs1 modules, and thus saves time. if, however, you are downloading basic stamp 1 code, the download function will attempt to locate bs1 modules regardless of the setting of this checkbox. this feature can also be found and modified via the preferences editor operation tab. like the identification function, the download function provides information to help guide you through the downloading process. after entering the desired source code in the editor window, you may run it in one of three ways: select run ?
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 49 to the basic stamp module (assuming the code is correct and the basic stamp is properly connected). the download progress window looks similar to the identify window with the exception of the additional download status progress bar, and the indicator led by the port transmitting the data. figure 3.11: the download progress window. if any errors occur, such as communica tion failure or inability to detect a basic stamp module, you will be prom pted appropriately. one possible error occurs when the basic stamp your pbasic program is targeting does not appear to be connected to th e pc (see figure 3.12). this may be caused, for example, by opening up a basic stamp 1 program (usually has a .bas or .bs1 extension) and trying to download it to a basic stamp 2 module, instead. figure 3.12: a download error message. when this happens, you?ll be prompted to correct the situation, quickly done by clicking on the bs2 button (if you really intended to download to the bs2 in the first place). keep in mind that programs written for one basic stamp model may not function properly on a different basic stamp model. click on the more info button for more detail. note: if you select the bs2 button, as in this example, the editor will modify the
using the basic stamp editor page 50 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com $stamp directive in the program, notify you of this change and what it means, and then will try to download to the bs2. another possibility is having two or more of the same basic stamp model connected to the pc. in this case, the editor will prompt you for clarification as to which basic stamp module you want to download to. in this case using a $port directive in your code will save you some tedium in repeatedly responding to such prompts. the basic stamp editor also features a memory map that displays the layout of the current pbasic program. type ctrl+m, or press f7, to activate this window. when you activate the memory map, the editor will check your program for syntax errors and, if the program?s syntax is okay, will present you with a color-coded map of the ram and eeprom. you?ll be able to tell at a glance how much memory you ha ve used and how much remains. figure 3.13: memory map for demo program data.bs2. the memory map is divided into two sections, the ram map and the eeprom map. the ram map shows how much of each register has been allotted to program variables. the ram legend details how much is used by i/o pins, word, byte, nibble and bit variables, and how much is unused. m emory m ap f unction . t he ram m ap .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 51 the eeprom map is shown in two scales. the main view is the detailed eeprom map, which displays the data in hexadecimal format in each location. the condensed eeprom map is the vertical region on the left that shows a small-scale view of the en tire eeprom; the red square over it corresponds to the scroll bar handle in the detailed eeprom map and indicates the portion of the eeprom that is currently visible in the detailed eeprom map. checking the display ascii checkbox switches the detailed eeprom display from hexadecimal to ascii. in this program, the textual data can be read right off the eeprom ma p when using this option. two important points to remember about this map are: 1) it only indicates how your program will be downloaded to the basic stamp module; it does not "read" the basic stamp memory, and 2) for all bs2 models, fixed variables like b3 and w1 and any aliases do not show up on the memory map as memory used. the editor igno res fixed variables when it arranges automatically allocated variables in memory. remember, fixed and allocated variables can overlap. the debug terminal window provides a convienent display for data received from a basic stamp during run-time, and also allows for the transmission of characters from the pc keyboard to the basic stamp. the debug terminal is automatically opened and configured when a pbasic program, containing a debug command, is downloaded. you can manually open a debug terminal one of three ways: select run new, press ctrl+d on the keyboard, or click on the debug terminal toolbar button. up to four (4) debug terminals can be open at once (on four different ports) and all can be left open while editing and downloading source code. figure 3.14 below shows the demo program debug_debugin.bs2 in the edit pane, and the debug terminal that opens when this program is run. t he d ebug t erminal . t he eeprom m ap .
using the basic stamp editor page 52 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com figure 3.14: demo program using the debug terminal the text in the debug terminal?s receive pane (blue area) prompts the user to enter a number into the transm it pane (white area) . after typing the number 10 and pressing enter, th e receive pane displays the number in decimal, hexadecimal, and binary format as dictated by the program (figure 3.15). figure 3.15: debug terminal output after entering a number. the fields across the top of the debug terminal window allow configuration of the communication port settings. these fields will be automatically configured and disabled if the debug terminal was p ort s ettings and s tatus .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 53 automatically opened by the editor, however, if manually opened, these fields will be enabled to allow manual configuration. the signal status leds turn bright green when activity on the indicated port line is detected. the signal checkboxes (dtr and rts) can be selected to set or clear the respective output line on the port. the echo off checkbox (bottom of window) causes the receive pane to throw away the characters that arrive in the port?s receive buffer immediately after transmitting characters from the transmit buffer. this produces a cleaner receive pane displa y for interactive programs such as the example above. keep in mind, ho wever, that this feature does not verify that the character it throws away is actually a match to a character that was just transmitted (because da ta collisions on the port can cause echoed characters to be garbled). you should only use the echo off feature in situations where it is requ ired, as it may result in a strange display in certain applications. there are keyboard shortcuts for severa l coding functions, some of which are unique to the basic stamp editor. table 3.6: coding function keyboard shortcuts. coding functions shortcut key(s) function ctrl+j show code templates. f6 or ctrl+i identify basic stamp firmware. f7 or ctrl+t perform a syntax check on the code and display any error messages. f8 or ctrl+m open memory map window. f9 or ctrl+r tokenize code, download to the basic stamp and open debug window if necessary. f11 or ctrl+d open a new debug window. f12 switch to next window (editor, debug #1, debug #2, debug #3 or debug #4) ctrl+1, ctrl+2, ctrl+3, ctrl+4 switch to debug terminal #1, debug terminal #2, etc. if that terminal window is open. ctrl+` switch to editor window. esc close current window. the basic stamp editor includes search able, indexed help files. access help by selecting help
using the basic stamp editor page 54 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com figure 3.16: the help file contains the complete pbasic syntax documentation. the current help files contain the entire pbasic syntax documentation. in addition, the example demo code programs that appear after most command descriptions in chapter 5 ar e automatically placed in default directories during the basic stamp editor v2.2 installation. these programs can be accessed via hyperlinks within the help file. note: the basic stamp editor help file requires microsoft's html help utility and internet explorer 4. 0 or above (ie 6.0 recommended). the proper version of html help is included with windows 2000 and windows xp. on other versions of windows you may have to install or upgrade your html help utility to properly view the stamp editor?s on-line help. the html help upgrade program (hhupd.exe) is included as part of the basic stamp editor setup program and the editor will automatically prompt you to run it if it determines you need to upgrade. you can download the latest version of internet explorer from microsoft?s web site at www.microsoft.com. h elp f iles require m icrosoft ? s html h elp utility .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 55 the tip of the day function displays a new message each time you run the basic stamp editor. there are many useful tips, and you may browse through them any time with the next tip and previous tip buttons. you may also use the edit tips option to ch ange the contents of any tip. all tips are contained in a single file, named stamp_tips.txt, that is stored in the editor?s installation direct ory, usually a path similar to c:\program files\parallax inc\stamp editor v2.2. figure 3.17: tip of the day #24. you can turn this feature off by unch ecking the show tips on startup box at the bottom of the window. to access it again, choose help setting preferences the basic stamp editor allows the user to set preferences for the appearance and operation of many aspects of the application. select edit
using the basic stamp editor page 56 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com preferences are specific to the editor, and are not saved as part of any basic stamp program that you may have open while setting preferences. figure 3.18: the editor appearance tab under edit
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 57 to create a custom scheme, select a default scheme you wish to modify, and click on the copy scheme button. then, select (highlight) an element within the syntax element list, and apply new text attributes with the checkboxes and drop-down menus to the right. as you try various text attributes and color combinations, the show preview example checkbox lets you audition your custom sche me without closing the preferences window. the basic stamp editor supports one custom scheme at a time. it can be modified indefinitely, but it cannot be copied. if you again copy a default scheme, you will be asked to confirm that you wish to overwrite your current custom scheme. under this tab, you will also find checkboxes that allow you to show or hide bookmarks, line numbers, the overwrite cursor, and the toolbar. under the editor operation tab (figur e 3.19), you may set preferences for automatic indentation and tab behavior. the auto indent on enter option makes it easy to indent nested loops to make code easier to read. the auto unindent option enables quick reversal of an indented line by simply using the backspace key, provided that the cursor is to the left of the first character on the line. the editor lets you choose whether a tab character or spaces are inserted into source code whenever you press the tab key. the default setting, insert space characters upon tab key presses, is recommended because it enforces the intended formatting regardless of what editor you use to view the code later. c ustomized s yntax h ighlighting . e ditor o peration p references . a uto i ndenting / u nindenting . t ab c haracter .
using the basic stamp editor page 58 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com in addition to the actual character used for the tab key, there are three behaviors of tabbing employed by th e editor: smart tabs, fixed tabs and fixed plus smart tabs. figure 3.19: the editor operation tab under edit
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 59 make the tab key move the cursor to positions, 3, 5, 7, 9 and 11, then afterwards, 13, 15, 17, 19, etc. (a multiple of two (11 ? 9 = 2) after the last listed position. the last option is a mixture of th e first two, fixed plus smart tabs (figure 3.22); it is the default and recommended setting. fixed plus smart tabs will cause the tab key to move the cursor to the position indicated by the fixed tab positions field, or if th e position is already beyond the end of that list, it reverts to smart tabs behavior. this setting, combined with a carefully configured fixed tab positions field, allows for a fixed level of indenting on the left side of the sour ce code (for executable code blocks), with very flexible indenting to the right of executable code (for comments that appear to the right of code). the default settings provide a quick, single-key method of indenting up to five (5) levels of executable code and easy alignment of multiple lines of comments to the right of that code. figure 3.20: smart tabs. figure 3.21: fixed tabs. figure 3.22: fixed plus smart tabs. f ixed plus s mart t abs .
using the basic stamp editor page 60 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the fixed tab positions list is used to provide a list of desired fixed tab positions (used with fixed tabs or fi xed plus smart tabs options). the list can be a single number, or a list of comma separated numbers in ascending order. the allowable range is 2 to 512 and the list size is virtually unlimited. when multiple values are entered, the difference between the last two values will be used to set tab positions beyond the last position. for example, in the de fault list, the last two positions are 9 and 11; resulting in further tab position s of 13, 15, 17, etc. (multiples of 2 after the last specified position). since source code is usually indented by multiples of two (2) spaces, the default list of 3, 5, 7, 9 and 11 is recommended. the default com port setting allows you to specify which com port to download through. if you specify a sp ecific port here, the identification window will report that it is ?ignorin g? other known ports. this can be selectively overridden by placing a $port directive in the program. if this setting is left on ?auto?, the defa ult, the editor will open and scan all known ports for the correct basic stamp. the button to the right, labeled ?...?, opens the a window allowing the known port list to be edited. modifying the known port list only affects which ports the basic stamp editor tries to use; it does not affect which serial ports are installed on your computer. it is recommended that you delete all known modem ports and any problematic ports from this list. for an explanation of the default pr oject download modes, see table 3.7 on page 70. this is part of a discussion on basic stamp projects in the advanced compilation techniques beginning on page 68, below. selecting the ?ignore bs1 modules unless downloading bs1 source code? checkbox optimizes identification sp eed by attempting to locate bs1 modules only if you are downloading basic stamp 1 code. this feature can also be activated via the iden tification or download window. under the files and directories tab (figure 3.23), you can set preferences for saving and accessing files, as we ll as automaticall y creating backup copies. t he f ixed t ab p ositions l ist . d efault com p ort . t he f iles and d irectories t ab .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 61 figure 3.23: the files and directories tab under edit
using the basic stamp editor page 62 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com into a single basic stamp editor, in cluding an editor that is already running. the ?multiple editors? option will cause a new basic stamp editor to open each time you open an associated basic stamp file from any explorer-shell. also, by associating basic stamp source code with the editor, windows will provide an ?open with stamp edito r? option when right-clicking on that source code from any explorer-shell. the ?new file template? field allows you to specify a file to load each time the file i nitial d irectory on s tartup . m odule d irectories . o pen w ith s tamp e ditor option . n ew f ile t emplate feature .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 63 you may use the clear and browse? buttons under the module directories list to select new default directory locations for each model of basic stamp. these new folders will then appear as options when you use the file open from... and file open from... and file f avorite d irectories . d ebug a ppearance p references . the c hoose ... b uttons .
using the basic stamp editor page 64 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com figure 3.24: the debug appearance tab under edit
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 65 the screen. if the default is used, fo r example, you could receive 1024 lines worth of text from a basic stamp, and still be able to scroll back and view the first line that was received. upon receiving the 1025 th line of text, the first line of text is pushed out of the buffer and is lost for good, making the first visible line in the receive pane actually be the 2 nd line of text that was received. larger buffer sizes consum e more pc memory (256 * buffer_size * number_of_open_debug_terminals bytes), so it is best to set it only as high as you need it for your application. the tab size can be adjusted as well, anywhere from 3 to 16 character spaces. the default is 8. keep in mind that most people don?t change this value, so writing code that relies on a particular setting other than 8 may display improperly on other user?s debug terminals.
using the basic stamp editor page 66 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com under the debug function tab (figure 3.25), checkboxes allow enabling or disabling of special processing for 16 different control characters. the default is for all 16 control characters to be processed, but you may disable one or more of them if you are using the debug terminal to view data coming from a device other than a basic stamp. figure 3.25: the debug function tab under edit
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 67 under the debug port tab (figure 3.26), each of the four (4) debug terminal?s default com port setting s may be configured separately. these settings are only used when the debug terminal is manually opened. figure 3.26: the debug port tab under edit
using the basic stamp editor page 68 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com advanced compilation techniques for bs2e, bs2sx, bs2p, bs2pe and bs2px modules, each editor page can be a separate project, or part of a single project. a project is a set of up to eight files that should all be downlo aded to the basic stamp for a single application. each of the files with in the project is downloaded into a separate "program slot". only the basic stamp 2e, 2sx, 2p, 2pe, and 2px modules support multi-file projects. for basic stamp projects (consisting of multiple programs), the $stamp directive has an option to specify addi tional filenames. the syntax below demonstrates this form of the $stamp directive: ' { $stamp bs2e, file2, file3, ?, file8 } use this form of the $stamp directive if a project, consisting of multiple files, is desired. this form of the directive must be entered only into the first program (to be downloaded into program slot 0). the file2 , file3 , etc. items should be the actual name (and optionally the path) of the other files in the project. file2 refers to the program that should be downloaded into program slot 1, file3 is the program that should be downloaded into program slot 2, etc. if no path is given, the filename is given the path of program 0 when loading them into the editor. up to seven filenames can be included, bringing the total to eight files in the project all together. upon load ing, tokenizing, running or viewing program 0 in the memory map, the edit or will read the $stamp directive, determine if the indicated files exist, will load them if necessary and change their captions to indicate th e project they belong to and their associated program number. after the directive is tokenized properly, and all associated files are labeled properly, tokenizing, running or viewing any program in the memory map will result in that program?s entire project being tokenized, downloaded or viewed. when program #0 of a multi-file project is opened from diskette, the entire project will be loaded (all referenced file s) as well. when a file that is part of a multi-file project is closed, the en tire project (all the associated files) will be closed as well. i ntroduction to basic s tamp p rojects . u sing the $stamp directive to define multi - file projects .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 69 to create a project consisting of multiple files, follow these steps: 1. create the first file in the editor and save it (we'll call it sample.bsx). this will be the program that is downloaded into program slot 0. 2. create at least one other file in th e editor and save it also (we'll call it nextprogram.bsx). note: at this point the editor tabs will be: 0:sample.bsx and 0:nextprogram.bsx. indicating that there are two unre lated files open "sample.bsx" and "nextprogram.bsx" and each will be downloaded into program slot 0. 3. go back to the first program an d enter or modify the $stamp directive using the project format. use "nextprogram" as the file2 argument. for example: ' {$stamp bs2sx, nextprogram.bsx} 4. then tokenize the code by pressing f7 or selecting run check syntax from the menu . at this point, the basic stamp edi tor will see the $stamp directive and realize that this file (sample.bsx) is the first file in a project and that the second file should be nextprogram.bsx. it will then search for the file on the hard drive (to verify its path is correct), will see that it is already loaded, and then will change the editor tabs to indicate the project relationship. at this point the editor tabs will be: 0:sample.bsx and [sample] 1:nextprogram.bsx. indicating that there are two rela ted files open; "sample.bsx" and "nextprogram.bsx". nextprogram.bsx belongs to the "sample" project and it will be downloaded into program slot 1 and sample.bsx will be downloaded into program slot 0. e asy s teps to c reating m ulti -f ile p rojects .
using the basic stamp editor page 70 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the editor has the ability to treat projects as one logical unit and can download each of the associated source code files at once. in order to minimize download time for large projects a project download mode is available in the preferences window. the available modes are: ?modified? (the default), ?all? or ?current? and are explained below. this item only affects download operations for the bs2e, bs2sx, bs2p and bs2pe. see table 3.7. download mode function modified (default) this mode will cause only the source code files that were modified since the last download to be downloaded next time. if no files have been modified since the last download, or the entire project has just been loaded into the editor, all the files will be downloaded next time. this mode decreases the delay during downloading projects and should help speed development and testing. all this mode will cause all the source code files to be downloaded each time. this will be noticeably slow with large projects. current this mode will cause only the current source code file to be downloaded, ignoring all the others. this mode can be helpful, but can lead to development errors if you forget to download a required program. table 3.7: project download modes. regardless of the download mode selected, the programs will be downloaded into the program sl ot indicated in their tab. some source code may be suitable for multiple uses but requires changing a set of constants as needed for each case. for example, you may want to run the same program on a bs2 and a bs2sx, but the resolution of time- sensitive commands is different, requiring slight code modifications. several conditional compile directives exist in pbasic 2.5 to assist with this situation. table 3.8 lists the available directives. directive function #define allows the programmer to create custom symbols for use within conditional compilation control structures. #if...#then...#else evaluate condition and, if it is true, compile the statement(s) following #then, otherwise compile the statements following #else. #select...#case evaluate expression and then condi tionally compile a block of code based on comparison to co ndition(s). if no conditions are found true and a #case else block is included, the #case #else code statements will compiled. #error allows the programmer to create a custom error dialog. table 3.8: conditional compile directives. note: these directives require pbasic 2.5. p roject d ownload m odes . c onditional c ompile d irectives .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 71 lets look at the syntax and examples for each conditional compile directive. for an explanation of syntax conventions, see page 128. #define symbol { = value } #define allows the programmer to create custom, compile-time, symbols for use within conditional compile control structures. ? symbol is a unique symbol name that will optionally represent a value . ? value is an optional constant/e xpression specifying the value of symbol . if the value parameter is omitted, symbol is defined as true (-1). example: ' {$pbasic 2.5} #define debugmode #if debugmode #then debug "debugging." stop in the example above, the #define statement defines debugmode to be ?true? (-1), since there is no value argument provided. the second line is another conditional comp ile statement, #if?#then (see below for more information) which evaluates the state of debugmode, determines it is true and then allows the following debug statement to be compiled into the program. the last line, stop, is compiled into the program afterwards. the result of compiling this example is a program with only two executable statements, debug "debu gging", cr and stop. the real power of this example, however, is more obvious when you comment out, or remove, the #define line. look at the next example, below: ' {$pbasic 2.5} ' #define debugmode #if debugmode #then debug "dubugging." stop here we commented out the #define line, effectively removing that line from the program. this means that the symbol debugmode will be undefined, and undefined conditional compile symbols are treated as #define s yntax .
using the basic stamp editor page 72 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com false (0). upon compiling this ex ample, the #if?#then statement will evaluate debugmode , which is false (because it is undefined) and then will not allow the debug statement to be compiled. only the stop command will be compiled into the program in this example. this is a very powerful feature for quickly removing many debug statements (or other statements) from a program when you?re done developing it, but leaving the possibility of re-enabling all those statements should further maintenance be required at a later time. the optional value argument can be used, for example, to select modes of operation: ' {$pbasic 2.5} #define systemmode = 2 #if systemmode = 1 #then high 1 #else low 1 #endif in the example above, the first line defines systemmode to be equal to 2. the #if?#then statement evaluates the state of systemmode , determines it is 2, so the condition is false, an d then it skips the statement after #then and allows the statement following #else to be compiled into the program. note, conditional compile directives are evaluated just before the program is compiled, so variables and named co nstants cannot be referenced within a conditional compile definition. compile-time symbols created with #define can, however, be referenced by conditional compile commands. #if condition(s) #then statement(s) { #else statement(s) } #endif #if...#then s yntax .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 73 #if?#then is a conditional compile structure similar to the run-time if?then command except that, at compile time, #if?#then evaluates condition(s) and, if it is true, compiles the statement(s) following #then, otherwise it compiles the statement(s) following #else. ? condition is a statement that can be evaluated as true or false during compile-time. ? statement is any valid pbasic instruction. example: ' {$pbasic 2.5} ' set baud for 9600-n81 #if ($stamp = bs2sx) or ($stamp = bs2p) #then baud con 16624 #else #if ($stamp = bs2px) baud con 16780 #else baud con 16468 #endif #endif in this example, the constant baud is set to an appropriate value for the basic stamp that is specified in the $stamp directive (not shown). this code will work with the bs2, bs2e , bs2sx, bs2p, bs2pe, and bs2px. one important thing to note is that th e $stamp directive is used here as a compile-time symbol, as if it were defined by #define. the compiler treats all the editor directives, $stamp, $pbasic and $port as ?defined? compile-time symbols set equal to th e respective value used in their declaration. at the time of this writing, using $pbasic in this fashion is pointless since the conditional-compile directives are only supported in pbasic 2.5, and would cause an error if compiled in any other version of the language.
using the basic stamp editor page 74 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com #select expression #case condition(s) statement(s) { #case condition(s) statement(s) #case #else statement(s) } #endselect #select?#case is a conditional compile structure similar to the run- time select?case command except that, at compile time, #select?#case evaluates expression and then conditionally compiles a block of code based on comparison to condition(s) . if no c onditions are found to be true and a #case #else block is included, the statement(s) in the #case #else block will be compiled. ? expression is a statement that can be evaluated as true or false during compile-time. ? condition is a statement, that when compared to expression , can be evaluated as true or false. multiple conditions within the same case can be separated by commas ( , ). ? statement is any valid pbasic instruction. example: ' {$pbasic 2.5} #select $stamp #case bs2, bs2e, bs2sx gosub lcd_write #case #else lcdout lcdpin, cmd, [char] #endselect this example checks the $stamp di rective at compile-time and either compiles gosub lcd_write - or ? lcdout lcdpin, cmd, [char] into the program. #select...#case s yntax .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 75 #error message #error displays a compile-time error. this allows the programmer to flag fatal errors during compilation. ? message is the error message string, enclosed in quotes. example: ' {$pbasic 2.5} #define i2cready = (($stamp = bs2p) or ($stamp = bs2pe) or ($stamp = bs2px)) #if not i2cready #then #error "bs2p, bs2pe, or bs2px is required for this program." #endif when compiled, this exampl e will cause the editor to halt compilation and display the dialog below if you attempt to compile for a basic stamp model other than the bs2p, bs2pe, or bs2px: figure 3.27: custom error message using the #error directive. features for developers the basic stamp editor has several features that are designed to support the needs of developers. note: when installing the basic stamp editor, you can instruct the installer to include additional developer resources by selecting the ?custom? option from the ?setup type? prompt. the generate object code feature allows you to tokenize a pbasic program and save it to a file in the tokenized form. this allows you to send your basic stamp object code (the actual binary data that is downloaded to the basic stamp module) to other people without having to reveal your pbasic source code. if you are a developer who has #error syntax . g enerate o bject c ode f eature .
using the basic stamp editor page 76 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com customers using basic stamp-based products, you can release firmware updates to them in this manner. object code can be saved as a separa te .obj file (downloadable with the stamploader.exe program) or as a single executable (integrated with the stamploader.exe inside of it). the single executable method provides a simpler way to pass your firmware update on to your customers. any syntactically correct pbasic source code can be used with the generate object code feature; this in cludes bs1 and bs2 code as well as bs2e, bs2sx, bs2p, bs2pe, and bs2px code that is either a single file or a multi-file project. note: the original dos-based software for the bs1 included a directive called bsave; wh en used it would cause the software to generate an object file. in the basic stamp windows editor, the generate object code feature replaces and enhances the bsave feature; the reserved word bsave is still accepted in bs1 source code, but is simply ignored. old bs1 object code saved via the bsave option is not compatible with the stamploader.exe program so you must regenerate the object file using the basic stamp windows editor. if you don?t have the stamploader.ex e program, it can be automatically generated for you by selecting the seco nd output file option, ?object code and stamp loader?, in the generate object code window. additionally, firmware, product, company and related info can be embedded in the object code or single executable file for your customers to view before downloading.
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 77 figure 3.28: the generate object code window. in the example above, we chose to generate a single executable with custom names and messages as shown. then we clicked the generate? button (which prompted us for a file name) and the file was created. when a user runs the file we just generated, they see a screen similar to the figure below: figure 3.29: example customized stamploader.exe file.
using the basic stamp editor page 78 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com another feature of interest to so me developers is the basic stamp editor?s command line interface. th is interface provides for command line, batch file or third-party driven control of the editor. the stampw.exe program is a win32 application that can be run through any standard method. when run with the command-line options, however, it provides special features that developers and product manufacturing managers may find usef ul. while this program can be run from a command prompt on a window s system, it will not work on a dos-only system. the stampw.exe supports redirection of its input and output via the standard pipe mechanisms. if its output is redirected via the command- line (ex: stampw.exe myfile.bs2 > test1.txt) the designated output file, test1.txt in this case, will be created and various information about the processing of the source file will be st ored there. this information directly reflects the information available on the gui prompts, interactions with the user and downloading status. this feature can be combined with the /nodebug and /noprompts switches for various levels of gui interaction with the user; including completely hidden operation. the following is the syntax of the basic stamp editor?s command-line switches. stampw.exe {/com#} {{/readonly} source_file} stampw.exe {/com#} /download {/updates}{/nodebug}{/noprompts} source_file > output_file stampw.exe {/com#} /identify {/noprompts} > output_file stampw.exe /tokenize source_file > output_file stampw.exe /pipe master_file stampw.exe /help table 3.9 gives a function descript ion for each command-line switch. c ommand l ine i nterface .
3: using the basic stamp editor basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 79 table 3.9: command line switches command function /com# specify com port (serial port) to download to. # is a valid com port number. note: must be one word, i.e.: com2 indicates com port 2. /readonly open source_file in read-only mode. the ctrl key acts as a download key when in read-only mode. requires source_file argument. this command option is not available if double- piped communication is established. /identify identify basic stamp modules on com ports. requires redirection to output_file . /tokenize tokenize source code. no prompts will be displayed. requires source_file argument and redirection to output_file . /download tokenize source code, and download it (if tokenization successful). requires source_file argument and redirection to output_file . /updates provides program slot number (if applicable) and download-percentage- complete status updates during download. /nodebug no debug terminal opens after downloading (even if code contains debugs) and com port is immediately closed after downloading. this option requires /download switch. note: this switch will have no effect if debug terminal is already open from a previous operation. /noprompts no screen prompts at all (except for debug terminal). this option requires /download switch. /pipe master_file start up master_file (must be .exe) and establish bi-directional communication pipes (double-piped communication) for master-program- controlled execution. stampw.exe remains open until master_file breaks pipe. this command option is not available once double-piped communication is established. /help display command-line help. this co mmand option is not available if double- piped communication is established. when the output of the basic stamp edit or is piped to a file or a master program, it displays all of its messag es in a specific, predefined format. each message has a unique 3-digit number. detailed information about the use of command-line options, including a table of all messages with their id numbers, can be found in the ?what?s new in stamp.exe? document included with the typical installation of the stamp editor.
using the basic stamp editor page 80 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
4: basic stamp architecture ? memory organization basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 81 basic stamp architecture introduction this chapter provides detail on the architecture (ram usage) and math functions of the bs1, bs2, bs2e, bs2sx, bs2p, bs2pe, and bs2px. the following icons will appear to in dicate where there are differences among the various ba sic stamp models: one or more of these icons indicates the item applies only to the bs1, bs2, bs2e, bs2sx, bs2p, bs2pe, or bs2px respectively. if an item applies to the all of the models in the bs2 family, this icon is used. the basic stamp has two kinds of me mory; ram (for variables used by your program) and eeprom (for st oring the program itself). eeprom may also be used to store long-ter m data in much the same way that desktop computers use a hard drive to hold both programs and files. an important distinction between ram and eeprom is this: ? ram loses its contents when the basic stamp loses power; when power returns, all ram locations are cleared to 0s. ? eeprom retains the contents of memory, with or without power, until it is overwritten (such as during the program-downloading process or with a write instruction.) the bs1 has 16 bytes (8 words) of ram space arranged as shown in table 4.1 the first word, called port, is used for i/o pin control. it consists of two bytes, pins and dirs. the bits within pins correspond to each of the eight i/o pins on the bs1. reading pins effectively reads the i/o pins directly, returning an 8-bit set of 1's and 0's corresponding to the high and low state of the respective i/o pin at that moment. writing to pins will store a high or low value on the respective i/o pins (though only on pins that are set to outputs). the second byte of port, dirs, controls the direction of the i/o pins. each bit within dirs corresponds to an i/o pin's direction. a high bit (1) m emory o rganization ram o rganization (bs1) t he i nput /o utput v ariables . all 2 1
basic stamp architecture ? memory organization page 82 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com sets the corresponding i/o pin to an ou tput direction and a low bit (0) sets the corresponding i/o pin to an input direction. the remaining words (w0 ? w6) are available for general-purpose use. each word consists of separately a ddressable bytes and the first two bytes (b0 and b1) are bit addressable as well. you may assign other names (symbols ) to these ram registers as shown in section "defining and using variables", below. when the bs1 is powered up, or reset, all memory locations are cleared to 0, so all pins are inputs (dirs = %00000000). also, if the pbasic program sets all the i/o pins to outputs (dirs = %11111111), then they will initially output low, since the output latch (p ins) is cleared to all zeros upon power-up or reset, as well. word name byte names bit names special notes port pins dirs pin0 ? pin7 dir0 ? dir7 i/o pins; bit addressable. i/o pins directions ; bit addressable. w0 b0 b1 bit0 ? bit7 bit8 ? bit15 bit addressable. bit addressable. w1 b2 b3 w2 b4 b5 w3 b6 b7 w4 b8 b9 w5 b10 b11 w6 b12 b13 used by gosub instruction. used by gosub instruction. table 4.1: bs1 ram organization. note: there are eight words, consisting of two bytes each for a total of 16 bytes. the bits within the upper two words are individually addressable. the bs2, bs2e, and bs2sx models have 32 bytes of variable ram space arranged as shown in table 4.2. of these, the first six bytes are reserved for input, output, and direction contro l of the i/o pins. the remaining 26 bytes are available for general-purpose use as variables. the bs2p, bs2pe, and bs2px models have an extra set of ins, outs, and dirs registers for a total of 38 bytes of variable ram. these are ?shadow? registers that are switched in and out of the memory map with the auxio, mainio, and ioterm commands. while this feature exists in ram o rganization .
4: basic stamp architecture ? memory organization basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 83 the variable ram for these models, on ly the bs2p40 module has the extra 16 i/o pins for which this feature is intended. the word variable ins is unique in that it is read-only. the 16 bits of ins reflect the state of i/o pins p0 through p15. it may only be read, not written. outs contains the states of the 16 output latches. dirs controls the direction (input or output) of each of the 16 i/o pins. a 0 in a particular dirs bit makes the corresponding pin an input and a 1 makes the corresponding pin an output. so if bit 5 of dirs is 0 and bit 6 of dirs is 1, then i/o pin 5 (p5) is an input and i/o pin 6 (p6) is an output. a pin that is an input is at the merc y of circuitry outside the basic stamp; the basic stamp cannot change its state. a pin that is an output is set to the state indicated by the correspon ding bit of the outs register. when the basic stamp is powered up, or reset, all memory locations are cleared to 0, so all pins are inputs (dirs = %0000000000000000). also, if the pbasic program sets all the i/o pins to outputs (dirs = %1111111111111111), then they will initially output low, since the output latch (outs) is cleared to all zeros upon power-up or reset, as well. table 4.2: ram organization for all bs2 models. note: there are 16 words, of two bytes each for a total of 32 bytes*. all bits are individually addressable through variable modifiers; the bits within the upper three words are also individually addressable though the pre-defined names shown. all registers are word, byte, nibble and bit addressable. *the bs2p, bs2pe, and bs2px have an additional set of ins, outs, and dirs registers that are switched in and out of the memory map in place of the main ins, outs, and dirs registers by using auxio, mainio, and ioterm. only the bs2p40 has the required extra i/o pins this feature is intended for. word name byte names nibble names bit names special notes ins* inl, inh ina, inb inc, ind in0 ? in7 in8 ? in15 input pins outs* outl, outh outa, outb outc, outd out0 ? out7 out8 ? out15 output pins dirs* dirl, dirh dira, dirb dirc, dird dir0 ? dir7 dir8 ? dir15 i/o pin direction control w0 b0, b1 w1 b2, b3 w2 b4, b5 w3 b6, b7 w4 b8, b9 w5 b10, b11 w6 b12, b13 w7 b14, b15 w8 b16, b17 w9 b18, b19 w10 b20, b21 w11 b22, b23 w12 b24, b25 t he i nput /o utput v ariables .
basic stamp architecture ? memory organization page 84 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the ins variable always shows the state of the i/o pins themselves, regardless of the direction of each i/o pin. we call this, "reading the pins". if a pin was set to an input mode (within dirs) and an external circuit connected the i/o pin to gr ound, the corresponding bit of ins would be low. if a pin was set to an output mode and the pin's state was set to a high level (within outs), th e corresponding bit of ins would be high. if, however, that same pin wa s externally connected directly to ground, the corresponding bit of ins would be low; since we're reading the state of the pin itself and the basi c stamp cannot override a pin that is driven to ground or 5 volts externally. note: the last example is an error, is a direct short and can cause damage to the basic stamp! do not intentionally connect output pins direct ly to an external power source or you risk destroying your basic stamp. to summarize: dirs determines whether a pin?s state is set by external circuitry (input, 0) or by the state of outs (output, 1). ins always matches the actual states of the i/o pins, whet her they are inputs or outputs. outs holds bits that will only appear on pi ns whose dirs bits are set to output. in programming the basic stamp, it?s often more convenient to deal with individual bytes, nibbles or bits of ins, outs and dirs rather than the entire 16-bit words. pbasic has buil t-in names for these elements, shown in table 4.2. here's an example of what is described in table 4.2. the ins register is 16- bits (corresponding to i/o pins 0 though 15). the ins register consists of two bytes, called inl (the low byte ) and inh (the high byte). inl corresponds to i/o pins 0 through 7 and inh corresponds to i/o pins 8 though 15. ins can also be thought of as containing four nibbles, ina, inb, inc and ind. ina is i/o pins 0 though 3, inb is i/o pins 4 though 7, etc. in addition, each of the bits of ins can be accessed directly using the names in0, in1, in2? in5. the same naming scheme holds true for the outs and dirs variables as well. as table 4.2 shows, the basic stamp module?s memory is organized into 16 words of 16 bits each. the first three words are used for i/o. the remaining 13 words are available for use as general-purpose variables. p redefined "f ixed " v ariables . s ummary of the function of dirs, ins and outs.
4: basic stamp architecture ? defining variables basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 85 the 40-pin bs2p uses the first three words for i/o even though it has twice as many i/o pins. this is done with the auxio, mainio, and ioterm commands, which effectively switch the auxiliary i/o registers in and out of the ins, outs, and dirs locations. just like the i/o variables, the gene ral-purpose variables have predefined names: w0 through w12 and b0 through b25. b0 is the low byte of w0; b1 is the high byte of w0; and so on through w12 (b24=low byte, b25=high byte). unlike i/o variables, there?s no reason that your program variables have to be stuck in a specific posi tion in the basic stamp?s physical memory. a byte is a byte regardless of its location. and if a program uses a mixture of variables of different sizes, it can be difficult to logically dole them out or allocate storage. more importantly, mixing fixed variables with automatically allocated variables (discussed in the next section) is an invitation to bugs. a fixed variable can overlap an allocated variable, causing data meant for one variable to show up in another! the fixed variable names (of the general- purpose variables) are only provided for power users who require absolute access to a specific location in ram. we recommend that you avoid using the fixed variables in most situations. instead, let pbasic allocate variables as described in the next section. the editor software will or ganize your storage requirements to make optimal use of the available memory. before you can use a variable in a pbasic program you must declare it. ?declare? means letting the basic stamp know that you plan to use a variable, what you want to call it, and how big it is. although pbasic does have predefined variables that you can use without declaring them first (see previous sections), the preferred way to set up variables is to use the directive symbol (for the bs1) or var (for all bs2 models). here is the syntax for a variable declaration: symbol name = registername -- or -- name var size where name is the name by which you will refer to the variable, registername is the "fixed" name for the register and size indicates the d efining and u sing v ariables (var). 1 a ll 2 1 all 2 2 p
basic stamp architecture ? defining variables page 86 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com number of bits of storage for the vari able. note: the top example is for the bs1 and the bottom exampl e is for all bs2 models. there are certain rules regarding symbol names. symbols must start with a letter or underscore, can contain a mixture of letters, numbers, and underscore (_) characters, and must not be the same as pbasic reserved words, or labels used in your progra m. additionally, symbols can be up to 32 characters long. see appendix b fo r a list of pbasic reserved words. pbasic does not distinguish between upper and lower case, so the names myvariable, myvariable, and myvariable are all equivalent. for the bs1, the register name is one of the predefined "fixed" variable names, such as w0, w1, b0, b1, etc. here are a few examples of variable declarations on the bs1: symbol temporary = w0 ' value can be 0 to 65535 symbol counter = b1 ' value can be 0 to 255 symbol result = b2 ' value can be 0 to 255 the above example will create a variable called temporary whose contents will be stored in the ram location called w0. also, the variable counter will be located at ram location b1 and result at location b2. note that temporary is a word-sized variable (because that's what size w0 is) while the other two are both byte-sized variables. throughout the rest of the program, we can use the names temporary , counter , and result instead of w0, b1 and b2, respectively. this makes the code much more readable; it's easier to determine what counter is used for than it would be to figure out what the name b1 means. please note that counter resides at location b1, and b1 happens to be the high byte of w0. this means than changing counter will also change temporary since they overlap. a situation like this usually is a mistake and results in strange behavior, but is also a powerful feature if used carefully. for all bs2 models, the size argument has four choices: 1) bit (1 bit), 2) nib (nibble; 4 bits), 3) byte (8 bits), and 4) word (16 bits). here are some examples of variable declarations on the bs2 models: mouse var bit ' value can be 0 or 1. cat var nib ' value can be 0 to 15. dog var byte ' value can be 0 to 255. rhino var word ' value can be 0 to 65535. t he r ules of s ymbol n ames . 1 1 all 2 all 2
4: basic stamp architecture ? defining arrays basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 87 the above example will create a bit-sized variable called mouse , and nibble-sized variable called cat , a byte-sized variable called dog and a word-sized variable called rhino . unlike in the bs1, these variable declarations don't point to a specific location in ram. instead, we only specified the desired size for each va riable; the basic stamp will arrange them in ram as it sees fit. throughout the rest of the program, we can use the names mouse, cat, dog and rhino to set or retrieve the contents of these variables. a variable should be given the smallest size that will hold the largest value that will ever be stored in it. if you need a variable to hold the on/off status (1 or 0) of switch, use a bit. if you need a counter for a for?next loop that will count from 1 to 100, use a byte. and so on. if you assign a value to a variable that exceeds its size, the excess bits will be lost. for example, suppose you use the byte variable dog, from the example above, and write dog = 260 (%100000100 binary). what will dog contain? it will hold only the lowest 8 bits of 260: %00000100 (4 decimal). on all bs2 models, you can also define multipart variables called arrays. an array is a group of variables of the same size, and sharing a single name, but broken up into numbered ce lls, called elements. you can define an array using the following syntax: name var size(n) where name and size are the same as described earlier. the new argument, (n), tells pbasic how many elements you want the array to have. for example: mylist var byte(10) ' create a 10-byte array. once an array is defined, you can access its elements by number. numbering starts at 0 and ends at n-1. for example: mylist(3) = 57 debug ? mylist(3) this code will display "mylist(3) = 57" on the pc screen. the real power of arrays is that the index value can be a variable itself. for example: d efining a rrays . all 2
basic stamp architecture ? defining arrays page 88 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com mybytes var byte(10) ' define 10-byte array idx var nib ' define 4-bit var for idx = 0 to 9 ' repeat with idx = 0, 1, 2...9 mybytes(idx) = idx * 13 ' write idx * 13 to each cell next for idx = 0 to 9 ' repeat with idx = 0, 1, 2...9 debug ? mybytes(idx) ' show contents of each cell next stop if you run this program, debug will display each of the 10 values stored in the elements of the array: mybytes(0) = 0*13 = 0, mybytes(1) = 1*13 = 13, mybytes(2) = 2*13 = 26 ... mybytes(9) = 9*13 = 117. a word of caution about arrays: if yo u?re familiar with other basics and have used their arrays, you have prob ably run into the ?subscript out of range? error. subscript is another term for the index value. it is out-of-range when it exceeds the maximum value for the size of the array. for instance, in the example above, my bytes is a 10-cell array. allowable index numbers are 0 through 9. if your program exceeds this range, pbasic will not respond with an error message. instead, it will access the next ram location past the end of th e array. if you are not careful about this, it can cause all sorts of bugs. if accessing an out-of-range location is bad, why does pbasic allow it? unlike a desktop computer, the basic stamp doesn?t always have a display device connected to it for di splaying error messages. so it just continues the best way it knows how. it?s up to the programmer (you!) to prevent bugs. clever programmers, ca n take advantage of this feature, however, to perform tricky effects. another unique property of pbasic arrays is this: you can refer to the 0th cell of the array by using just the arra y?s name without an index value. for example: mybytes var byte(10) ' define 10-byte array mybytes(0) = 17 ' store 17 to 0th cell debug ? mybytes(0) ' display contents of 0th cell debug ? mybytes ' also displays 0th cell all 2
4: basic stamp architecture ? aliases and modifiers basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 89 this feature is how the "string" capabilities of the debug and serout command expect to work. a string is simply a byte array used to store text. see "displaying strings (b yte arrays)" in the debug command description on page 166 for more information. an alias is an alternative name for an existing variable. for example: symbol cat = b0 ' create a byte-sized variable symbol tabby = cat ' create alias for cat -- or -- cat var byte ' create a byte-sized variable tabby var cat ' create alias for cat in this example, tabby is an alias to the variable cat . anything stored in cat shows up in tabby and vice versa. both names refer to the same physical piece of ram. this kind of alias can be useful when you want to reuse a temporary variable in different places in your program, but also want the variable?s name to reflect its function in each place. use caution, because it is easy to forget about the aliases; during debugging, you might end up asking ?how did that value get here?!? the answer is that it was stored in the variable?s alias. on all the bs2 models, an alias can also serve as a window into a portion of another variable. this is done using "modifiers." here the alias is assigned with a modifier that specifies what part to reference: rhino var word ' a 16-bit variable head var rhino.highbyte ' highest 8 bits of rhino tail var rhino.lowbyte ' lowest 8 bits of rhino given that example, if you write the value %1011000011111101 to rhino , then head would contain %10110000 and tail would contain %11111101. table 4.3 lists all the variable modifiers. pbasic 2.0 and 2.5 lets you apply these modifiers to any variable name and to combine them in any fashion that makes sense. for example, it will allow: rhino var word ' a 16-bit variable eye var rhino.highbyte.lownib.bit1 ' a bit a liases and v ariable m odifiers . 1 all 2 all 2
basic stamp architecture ? aliases and modifiers page 90 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com symbol definition lowbyte low byte of a word highbyte high byte of a word byte0 byte 0 (low byte) of a word byte1 byte 1 (high byte) of a word lownib low nibble of a word or byte highnib high nibble of a word or byte nib0 nib 0 of a word or byte nib1 nib 1 of a word or byte nib2 nib 2 of a word nib3 nib 3 of a word lowbit low bit of a word, byte, or nibble highbit high bit of a word, byte, or nibble bit0 bit 0 of a word, byte, or nibble bit1 bit 1 of a word, byte, or nibble bit2 bit 2 of a word, byte, or nibble bit3 bit 3 of a word, byte, or nibble bit4 ? bit7 bits 4 though 7 of a word or byte bit8 ? bit15 bits 8 through 15 of a word table 4.3: variable modifiers for all bs2 models. the common sense rule for combining modifiers is that they must get progressively smaller from left to right. it would make no sense to specify, for instance, the low byte of a nibble, because a nibble is smaller than a byte! and just because you can stack up modifiers doesn?t mean that you should unless it is the clearest way to express the location of the part you want get at. the example above might be improved: rhino var word ' a 16-bit variable eye var rhino.bit9 ' a bit although we?ve only discussed variab le modifiers in terms of creating alias variables, you can also use them within program instructions: rhino var word ' a 16-bit variable head var rhino.highbyte ' highest 8 bits of rhino rhino = 13567 debug ? head ' display alias variable head debug ? rhino.highbyte ' rhino.highbyte works too stop modifiers also work with arrays. for example: mybytes var byte(10) ' define 10-byte array mybytes(0) = $ab ' hex $ab into 0th byte debug hex ? mybytes.lownib(0) ' show low nib ($b) debug hex ? mybytes.lownib(1) ' show high nib ($a) all 2
4: basic stamp architecture ? aliases and modifiers basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 91 if you looked closely at that example, you probably thought it was a misprint. shouldn?t mybyte s.lownib(1) give you th e low nibble of byte 1 of the array rather than the high nibble of byte 0? well, it doesn?t. the modifier changes the meaning of the index value to match its own size. in the example above, when mybytes() is addressed as a byte array, it has 10 byte-sized cells numbered 0 through 9. when it is addressed as a nibble array, using mybytes.lownib(), it ha s 20 nibble-sized cells numbered 0 through 19. you could also address it as individual bits using mybytes.lowbit(), in which case it would have 80 bit-sized cells numbered 0 through 79. what if you use something other than a ?low? modifier, say mybytes.highnib()? that will work, bu t its effect will be to start the nibble array with the high nibble of mybytes(0). the nibbles you address with this nib array will all be contiguo us, one right after the other, as in the previous example. mybytes var byte(10) ' define 10-byte array. mybytes(0) = $ab ' hex $ab into 0th byte mybytes(1) = $cd ' hex $cd into next byte debug hex ? mybytes.highnib(0) ' show high nib of cell 0 ($a) debug hex ? mybytes.highnib(1) ' show next nib ($d) this property of modified arrays make s the names a little confusing. if you prefer, you can use the less-descriptive versions of the modifier names; bit0 instead of lowbit, nib0 instea d of lownib, and byte0 instead of lowbyte. these have exactly the same e ffect, but may be less likely to be misconstrued. you may also use modifiers with the 0t h cell of an array by referring to just the array name without the index va lue in parentheses. it?s fair game for aliases and modifiers, both in var directives and in instructions. on all bs2 models, if you?re working on a program and wondering how much variable space you have left, you can use the memory map feature of the editor (ctrl-m). see the "memory map" section of chapter 3 on page 50. t he m emory m ap
basic stamp architecture ? scratch pad ram page 92 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the bs2e, bs2sx, bs2p, bs2pe, and bs2px have some additional ram called scratch pad ram. the bs2e an d bs2sx have 64 bytes of scratch pad ram (0 to 63) and the bs2p, bs2pe, and bs2px have 136 bytes of scratch pad ram (0-135). scratch pad ram can only be accessed with the get and put commands and cannot have variable names assigned to it. table 4.4 shows the layout of all spram registers. notice that the highest locations in scratch pad ram (location 63 in the bs2e and bs2sx, locations 127-135 in the bs2p, bs2pe, and bs2px) are special-purpose, read-only locations th at always contain special run-time information. for example, the lowest nibble of location 63 (bs2e and bs2sx) or 127 (bs2p, bs2pe, and bs 2px) contains the number of the currently running program slot. this is handy for programs that need to know which program slot they exist in. in the bs2p, bs2pe, and bs2px, the high nibble of location 127 holds the slot designated for read and write; see the store command on page 449 for more information. s cratch p ad ram
4: basic stamp architecture ? scratch pad ram basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 93 table 4.4: layout of spram registers. note: scratch pad ram can only be accessed with the get and put commands. scratch pad ram cannot have variable names assigned to it. location bs2e and bs2sx bs2p, bs2pe and bs2px 0...62 general purpose ram general purpose ram 63 bits 0-3: active program slot number. general purpose ram 64..126 n/a general purpose ram 127 n/a bits 0-3, active program slot #. bits 4-7, program slot for read and write operations. 128 n/a polled input trigger status of main i/o pins 0-7 (0 = not triggered, 1 = triggered). 129 n/a polled input trigger status of main i/o pins 8-15 (0 = not triggered, 1 = triggered). 130 n/a polled input trigger status of auxiliary i/o pins 0-7 (0 = not triggered, 1 = triggered). 131 n/a polled input trigger status of auxiliary i/o pins 8-15 (0 = not triggered, 1 = triggered). 132 n/a bits 0-3: polled-interrupt mode, set by pollmode 133 n/a bits 0-2: polled-interrupt ?run? slot, set by pollrun. 134 n/a bit 0: active i/o group; 0 =main i/o, 1 = auxiliary i/o. 135 n/a bit 0: polled-output status (set by pollmode); 0 = disabled, 1= enabled. bit 1: polled-input status; 0 = none defined, 1 = at least one defined. bit 2: polled-run status (set by pollmode); 0 = disabled, 1 = enabled. bit 3: polled-output latch status; 0 = real-time mode, 1 = latch mode. bit 4: polled-input state; 0 = no trigger, 1 = triggered. bit 5: polled-output latch state; 0 = nothing latched, 1 = signal latched. bit 6: poll-wait state; 0 = no event, 1 = event occurred. (cleared by pollmode only). bit 7: polling status; 0 = not active, 1 = active.
basic stamp architecture ? constants and expressions page 94 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com suppose you?re working on a program called ?three cheers? that flashes leds, makes hooting sounds, and activates a motor that crashes cymbals together, all in sets of three. a po rtion of your pbasic program might contain something like: for counter = 1 to 3 gosub make_cheers next ... for counter = 1 to 3 gosub blink_leds next ... for counter = 1 to 3 gosub crash_cymbals next the numbers 1 and 3 in the code above are called constants . they are constants because, while the progra m is running, nothing can happen to change those numbers. this distinguishes constants from variables, which can change while the program is running. constants are not limited to the deci mal number system; pbasic allows you to use several numbering systems. see ?number representations? on page 96. you can assign names to constants in a fashion similar to how variables are declared. on a bs1, it is identical to variable declarations. for all bs2 models, use the con directive. here is the syntax: symbol name = constantvalue -- or -- name con constantvalue c onstants and c ompile - time e xpressions . 1 a ll 2 1 all 2 d efining and u sing c onstants (con).
4: basic stamp architecture ? constants and expressions basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 95 once created, named constants may be used in place of the numbers they represent. for example: symbol cheers = 3 ' number of cheers. for counter = 1 to cheers gosub make_cheers next -- or -- cheers con 3 ' number of cheers. for counter = 1 to cheers gosub make_cheers next that code works exactly the same as the corresponding for?next loop in the previous example. the editor software substitutes the number 3 for the symbol named cheers throughout your program. like variables, labels and instructions, constant names are not case sensitive; cheers , and cheers are identical to cheers. using named constants does not increa se the amount of code downloaded to the basic stamp, and it often improves the clarity of the program. weeks after a program is written, you may not remember what a particular number was supposed to represent?using a name may jog your memory (or simplify the detective work needed to figure it out). named constants also have another benefit. suppose the ?three cheers? program had to be upgraded to ?five cheers.? in the original example you would have to change all of the 3s to 5s. search and replace would help, but you might accidentally change some 3s that weren?t numbers of cheers, too. however, if you had made smart use of a named constant, all you would have to do is change 3 to 5 in one place, the constant's declaration: symbol cheers = 5 ' number of cheers. -- or -- cheers con 5 ' number of cheers. 1 all 2 1 all 2
basic stamp architecture ? number representations page 96 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com now, assuming that you used the constant cheers wherever your program needed ?the number of cheers,? your upgrade would be done. on all bs2 models, you can take this idea a step further by defining constants with expressions; groups of math and/or logic operations that the editor software solves (evaluates) at compile-time (the time right after you start the download and before the basic stamp starts running your program). for example, suppose the ?cheers? program also controls a pump to fill glasses with champagne. perhaps the number of glasses to fill is always twice the number of cheer s, minus 1 (another constant): cheers con 5 ' # of cheers glasses con cheers*2-1 ' # of glasses as you can see, one constant can be de fined in terms of another. that is, the number glasses depends on the number cheers. the expressions used to define consta nts must be kept fairly simple. the editor software solves them from left to right, and doesn?t allow you to use parentheses to change the order of evaluation. the operators that are allowed in constant expressions are shown in table 4.5. operator symbol description + add - subtract * multiply / divide << shift left >> shift right & logical and | logical or ^ logical xor table 4.5: operators allowed in constant expressions for all bs2 models. the basic stamp, like any computer, excels at math and logic. however, being designed for control applicat ions, the basic stamp does math a little differently than a calculator or spreadsheet program. this section will help you understand basic stamp numbers, math, and logic. in your programs, you may express a number in various ways, depending on how the number will be used and wh at makes sense to you. by default, the basic stamp recognizes numbers lik e 0, 99 or 62145 as being in our r un - time m ath and l ogic . n umber r epresentations . all 2 all 2 1 a ll 2
4: basic stamp architecture ? number representations basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 97 everyday decimal (base-10) system. however, you may also use hexadecimal (base-16; also called hex) or binary (base-2). since the symbols used in decimal, he x and binary numbers overlap (e.g., 1 and 0 are used by all; 0 through 9 apply to both decimal and hex) the editor software needs prefixes to te ll the numbering systems apart, as shown below: 99 ' decimal (no prefix) $1a6 ' hex (prefix ?$? required) %1101 ' binary (prefix ?%? required) the basic stamp also automatically converts quoted text into ascii codes, and allows you to apply names (symbols) to constants from any of the numbering systems. for example: symbol lettera = "a" ' ascii code for a (65) symbol cheers = 3 symbol hex128 = $80 symbol fewbits = %1101 -- or -- lettera con "a" ' ascii code for a (65) cheers con 3 hex128 con $80 fewbits con %1101 binary coded decimal (bcd) is a way to encode decimal digits that is easier to display or manipulate in some devices. each digit of the decimal number (0 ? 9) requires 4 bits (a nibble) to encode. for this reason, a bcd byte is always two decimal digits an d a bcd word is always four decimal digits. the basic stamp does no t support bcd natively, however, because of the way that bcd is en coded the bs2 models? hexadecimal prefix, and conversion formatters can be used as a shortcut for most bcd input/output operations as long as the digits used do not exceed valid decimal digits (0 ? 9). for example: bcdvalue con $4096 debug hex bcdvalue the first line creates a symbol, bcdvalue , that contains the binary form of the hexadecimal value $4096, which means the upper nibble contains the binary value for the decimal digit 4, the next nibble is 0, the next nibble is 9 1 all 2 h ex to bcd c onversion all 2
basic stamp architecture ? number representations page 98 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com and the last nibble is 6; this corresp onds exactly to the bcd form of the decimal number 4096. the second line in the above example uses the hex conversion formatter within the debug command (see debug, page 159) to output the bcd value 4096 to the debug terminal. the hex conversion formatter can also be used for input operations to convert a decimal value to bcd, as long as that decimal value is no greater than 2 digits for a byte-sized variable or 4 digits for a word-sized variable. for more information on constants, see the section "constants and compile-time expressions", above. with all bs2 models, some of the math or logic operations in a program are solved by the basic stamp. the edit or software solves operations that define constants before the program is downloaded to the basic stamp. the preprocessing that takes place before the program is downloaded is referred to as ?compile-time.? after the download is complete, the basic stamp starts executing your program; this is referred to as ?run -time.? at run-time the basic stamp processes math and logic operations involving variables, or any combination of variables and constants. because compile-time and run-time expr essions appear similar, it can be hard to tell them apart. a few examples will help: result var byte ' compile-time assignment cheers con 3 ' compile-time glasses con cheers * 2 - 1 ' compile-time oneninety con 100 + 90 ' compile-time notworking con 3 * result ' error: variables not allowed here result = glasses ' run-time result = 99 + glasses ' run-time result = oneninety + 1 ' "100 + 90" solved at compile-time ' oneninety + 1 solved at run-time result = 100 + 90 ' 100 + 90 solved at run-time notice that the last example is solved at run-time, even though the math performed could have been solved at compile-time since it involves two constants. if you find something like this in your own programs, you can save some program space in the eeprom by converting the run-time w hen is r un - time ? all 2 all 2
4: basic stamp architecture ? pin symbols basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 99 expression 100+90 into a compile-time expression like oneninety con 100+90. to sum up: compile-time expressions are those that involve only constants; once a variable is involved , the expression must be solved at run-time. that?s why the line ?notworking con 3 * result? would generate an error message. the con di rective works only at compile-time and result is a variable; variables are not allowed in compile-time expressions. now we know now to create vari ables and constant s (with var and con) but there is a third option if you?re using pbasic 2.5; pin-type symbols (with pin). pin is like var and con put together and represents an i/o pin. there are some situations where it is handy to refer to a pin using a variable (like in2 or out2) and also as a constant (2, in this case). the pin directive lets you define a context-sensitive symbol representing an i/o pin. depending on where and ho w this pin-type symbol is used determines whether it is treated as an i/o pin input variable, and i/o pin output variable or as a consta nt representing the pin number. let?s explore a simple example to see where this is useful. it is common practice to define constants for any number used in many places so that changing that number doesn?t create a maintenance hassle later on. if we were to use a constant symbol to represent an i/o pin, we might do something like this: ' {$pbasic 2.5} signal con 1 ' constant-type symbol representing i/o 1 input signal ' set signal pin to input wait: if signal = 0 then wait ' wait until signal pin = 1 here we define signal to represent our desired i/o pin, then we use the input command to set it to the input direction and later we check the state of the signal pin and loop (wait) wh ile it is equal to logic 0. this code has a common bug, however; the input command works as expected, because its pin argument requires a number representing the i/o pin, but d efining and u sing p ins with the pin directive . all 2
basic stamp architecture ? pin symbols page 100 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the condition argument in the if?then statement will always evaluate to false because signal is a constant equal to 1, and ?1 = 0? is false. what the user really meant to happen is something like: if in1 = 0 then wait because in1 is the input variable representi ng the current state of i/o pin 1. this situation is perfect for the pin directive: ' {$pbasic 2.5} signal pin 1 ' pin-type symbol representing i/o 1 input signal ' set signal pin to input wait: if signal = 0 then wait ' wait until signal = 1 we only changed one thing in this code: the con directive was changed to pin. now signal is a context-sensitive symbol that will be treated as a constant or as a variable depending on where it is used. in the input command signal is used as the pin argument, and since that argument requires a number representing the pin number, signal is treated as a constant equal to 1. in the if?then statement, signal is compared to another value (which implies that what signal represents is expected to change at run-time; i.e.: signal?s value is ?variable?) so signal is treated as a variable equal to the input variable for the defined pin (in1 in this case). as another example, consider the following code: ' {$pbasic 2.5} signal con 2 ' constant-type symbol representing i/o 2 output signal ' set signal pin to output signal = 1 ' set signal high here, again, this is a common bug; the output command will work as expected, but the signal = 1 statement generates a syntax error at compile- time. why the error? this is an assi gnment statement, meant to assign the value 1 to the item on the left, but the item on the left is a constant, not a variable, so it can not be changed at run-time. what the user was thinking when writing this was: out2 = 1 which sets the value of the output variable representing i/o pin 2 to logical 1 (high). here?s the solution: all 2
4: basic stamp architecture ? pin symbols basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 101 ' {$pbasic 2.5} signal pin 2 ' pin-type symbol representing i/o 2 output signal ' set signal pin to output signal = 1 ' set signal high the output command treats signal as a constant equal to 2 and the signal = 1 statement treats signal as a variable equal to the output variable for the defined pin (out2 in this case). you might be wondering why ?signal = 0? in the if?then statement of our first example treats signal as the input variable in1 and yet ?signal = 1? in our last example treats signal as the output variable out2 . the distinction is that the first example is a comparison and the second example is an assignment. comparisons need to ?read? expressions and then evaluate the comparison while as signments need to read expressions and then ?write? the results. since signal is to the left of the equal sign (=) in our assignment statement, it must be a variable we can write to, thus it must be treated as out2, in this case. what happens if our pin-type symbol is to the ri ght of the equal sign in an assignment statement? example: ' {$pbasic 2.5} signal1 pin 1 ' pin-type symbol representing i/o 1 signal2 pin 2 ' pin-type symbol representing i/o 2 input signal1 ' set signal1 pin to input output signal2 ' set signal2 pin to output signal2 = signal1 ' set signal2 pin to signal1 pin?s state in this case signal2 is treated as out2 and signal1 is treated as in1; left side must be written to and righ t side must be read from. if a pin-type symbol is used in a command, but not in the pin argument of that command, it will be treated as an input variable (i.e.: inx). note: it is very rare that you?ll need to use a pin-type symbol in this way. the following is a summary of behavi ors and uses of pin-type symbols. all 2 all 2
basic stamp architecture ? pin symbols page 102 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com pin_symbol behaves like a constant: 1. when used in a command?s pin argument. example: output pin_symbol 2. when used in the index of an array. example: myarray( pin_symbol ) = 25 pin_symbol behaves like an input variable (inx): 1. when used in a command?s non- pin argument that expects to read a variable/constant/expression. example: debug bin pin_symbol 2. when used in a command?s condition argument. example: if pin_symbol = 1 then? 3. when used to the right of the equal sign (=) in an assignment statement. example: ex: myvariable = pin_symbol + 1 pin_symbol behaves like an output variable (outx): 1. when used in a command?s non- pin argument that expects to write a result to a variable. example: lookup index, [0, 1, 1, 0, 1], pin_symbol 2. when used to the left of the eq ual sign (=) in an assignment statement. example: pin_symbol = 1 let?s talk about the four basic operat ions of arithmetic: addition (+), subtraction (-), multiplication (*), and division (/). you may recall that the order in which you do a series of additions and subtractions doesn?t affect the result. the expression 12+7-3+22 works out the same as 22-3+12+7. however, when multiplication or division are involved, it?s a different story; 12+3*2/4 is not the same as 2*12/4+3. in fact, you may have the urge to put pa rentheses around portions of those equations to clear things up. 1 a ll 2 b asic a rithmetic o perations
4: basic stamp architecture ? order of operations basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 103 the basic stamp solves math problems in the order they are written: from left to right. the result of each operation is fed into the next operation. so to compute 12+3*2/4, the basic stamp goes through a sequence like this: 12 + 3 = 15 15 * 2 = 30 30 / 4 = 7 since the basic stamp performs integer math (whole numbers only) 30 / 4 results in 7, not 7.5. we?ll talk more about integers in the next section. some other dialects of basic would compute that same expression based on their precedence of operators, wh ich requires that multiplication and division be done before additi on. so the result would be: 3 * 2 = 6 6 / 4 = 1 12 + 1 = 13 once again, because of integer math, the fractional portion of 6 / 4 is dropped, so we get 1 instead of 1.5. the bs1 does not allow parenthesis in expressions. unfortunately, all expressions have to be written so that they evaluate as intended strictly from left to right. all bs2 models, however, allow parentheses to be used to change the order of evaluation. enclosing a math operation in parentheses gives it priority over other operations. to make the basic stamp compute the previous expression in the convention al way, you would write it as 12 + (3*2/4). within the parentheses, the ba sic stamp works from left to right. if you wanted to be even more sp ecific, you could write 12 + ((3*2)/4). when there are parentheses within parentheses, the basic stamp works from the innermost parentheses outw ard. parentheses placed within parentheses are called ?nested parentheses." the basic stamp performs all math op erations by the rules of positive integer math. that is, it handles only whole numbers, and drops any fractional portions from the result s of computations. the basic stamp handles negative numbers usin g two's complement rules. i nteger m ath . 1 all 2 o rder of o perations .
basic stamp architecture ? math and operators page 104 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com all bs2 models can interpret twos complement negative numbers correctly in debug and serout instructions using formatters like sdec (for signed decimal). in calculations, however, it assumes that all values are positive. this yields correct result s with two?s complement negative numbers for addition, subtraction, and multiplication, but not for division. the standard operators we just discus sed: +, - ,* and / all work on two values; as in 1 + 3 or 26 * 144. the values that operators process are referred to as arguments. so we say that the add, subtract, multiply and divide operators take two arguments. operators that take two arguments are called ?binary? operators, and those that take only one argument ar e called ?unary? operators. please note that the term ?binary operator ? has nothing to do with binary numbers; it?s just an inconvenient coincidence that the same word, meaning ?involving two things ? is used in both cases. the minus sign (-) is a bit of a hybrid. it can be used as a binary operator, as in 8-2 = 6, or it can be used as a unary operator to represent negative numbers, such as -4. unary operators take precedence over binary operators; the unary operation is always performed first. for example, on all bs2 models, sqr is the unary operator for square root . in the expression 10 - sqr 16, the basic stamp first takes the square root of 16, then subtracts it from 10. most of the descriptions that follow say something like ?computes (some function) of a 16-bit value.? this does not mean that the operator does not work on smaller byte or nibble values, but rather that the computation is done in a 16-bit workspace. if the value is smaller than 16 bits, the basic stamp pads it with leading 0s to make a 16-bit value. if the 16-bit result of a calculation is to be packed into a smaller variable, the higher-order bits are discarded (truncated). keep this in mind, especially when you are working with two?s complement negative numbers, or moving values from a larger variable to a smaller one. for example, look at what happens when you move a two?s complement negative number into a byte (rather than a word): u nary and b inary o perators . n otes about the 16- bit workspace . all 2
4: basic stamp architecture ? math and operators, abs basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 105 value var byte value = - 99 debug sdec ? value ' show signed decimal result (157) we expected -99 to be displayed bu t what we got was 157. how did -99 become 157? let?s look at the bits: 99 is %01100011 binary. when the basic stamp negates 99, it converts the number to 16 bits %0000000001100011, and then takes the two?s complement, %1111111110011101. since we?ve asked for the result to be placed in an 8- bit (byte) variable, the upper eight bi ts are truncated and the lower eight bits stored in the byte: %10011101. now for the second half of the story. debug?s sdec modifier (for all bs2 models) expects a 16-bit, two?s compleme nt value, but we've only given it a byte to work with. as usual, it creates a 16-bit value by padding the leading eight bits with 0s: %00000000100 11101. and what?s that in signed decimal? 157. to fix this problem, always store values that are intended to be signed into a word-sized variable. table 4.1 lists the available unary operators. note: the bs1 only supports negative (-). table 4.1: unary operators. note: the bs1 only supports the negative (-) unary operator. operator description supported by: abs returns absolute value all except bs1 cos returns cosine in twos complement binary radians all except bs1 dcd 2 n -power decoder all except bs1 ~ inverse all except bs1 - negative all ncd priority encoder of a 16-bit value all except bs1 sin returns sine in twos complement binary radians all except bs1 sqr returns square root of value all except bs1 the absolute value operator (abs) converts a signed (two?s complement) 16-bit number to its absolute value. the absolute value of a number is a positive number representing the difference between that number and 0. for example, the absolute value of -99 is 99. the absolute value of 99 is also 99. abs works on two?s compleme nt negative numbers. examples of abs at work: a bsolute v alue : abs u nary o perators . all 2 1 a ll 2 all 2
basic stamp architecture ? cos, dcd, ~, - page 106 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com result var word result = -99 ' put -99 into result ' ...(2's complement format) debug sdec ? result ' display as a signed # debug sdec ? abs result ' display as a signed # the cosine operator (cos) returns the two?s complement, 16-bit cosine of an angle specified as an 8-bit ?binary radian? (0 to 255) angle. cos is the same as sin in all respects, except that the cosine function returns the x distance instead of the y distance. see ?sine: sin?, below, for a code example and more information. the decoder operator (dcd) is a 2 n -power decoder of a four-bit value. dcd accepts a value from 0 to 15, and returns a 16-bit number with the bit, described by value, set to 1. for example: result var word result = dcd 12 ' set bit 12 debug bin16 ? result ' display result (%0001000000000000) the inverse operator (~) complements (inverts) the bits of a number. each bit that contains a 1 is changed to 0 and each bit containing 0 is changed to 1. this process is also known as a ?bitwise not? and ?ones complement?. for example: result var byte result = %11110001 ' store bits in byte result. debug bin8 ? result ' display in binary (%11110001) result = ~ result ' complement result debug bin8 ? result ' display in binary (%00001110) the negative operator (-) negates a 16-bit number (converts to its twos complement). symbol result = w1 result = -99 ' put -99 into result ' ...(2's complement format) result = result + 100 ' add 100 to it debug result ' display result (1) -- or -- c osine : cos d ecoder : dcd n egative : - all 2 all 2 1 i nverse : ~
4: basic stamp architecture ? ncd, sin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 107 result var word result = 99 ' put -99 into result ' ...(2's complement format) debug sdec ? result ' display as a signed # result = -result ' negate the value debug sdec ? result ' display as a signed # the encoder operator (ncd) is a "prior ity" encoder of a 16-bit value. ncd takes a 16-bit value, finds the highest bit containing a 1 and returns the bit position plus one (1 through 16). if the input value is 0, ncd returns 0. ncd is a fast way to get an answer to the question ?what is the largest power of two that this value is greater than or equal to?? the answer ncd returns will be that power, plus one. example: result var word result = %1101 ' highest bit set is bit 3 debug ? ncd result ' show the ncd of result (4) the sine operator (sin) returns the two?s complement, 16-bit sine of an angle specified as an 8-bit binary radian (0 to 255) angle. to understand the sin operator more completely, let?s look at a typical sine function. by definition: given a circle with a radius of 1 unit (known as a unit circle), the sine is the y-coordinate distance from the center of the circle to its edge at a given angle. angles are measured relative to the 3- o'clock position on the circle, increasing as you go around the circle counterclockwise. at the origin point (0 degrees) the si ne is 0, because that point has the same y (vertical) coordinate as the circle center. at 45 degrees the sine is 0.707. at 90 degrees, sine is 1. at 180 degrees, sine is 0 again. at 270 degrees, sine is -1. the basic stamp sin operator breaks the circle into 0 to 255 units instead of 0 to 359 degrees. some textbooks call this unit a ?binary radian? or ?brad.? each brad is equivalent to 1.406 degrees. and instead of a unit circle, which results in fractional sine values between 0 and 1, basic stamp sin is based on a 127-unit circle. results are given in two?s complement form in order to accommodate negative values. so, at the origin, sin is 0. at 45 degrees (32 brads), sine is 90. at 90 degrees (64 brads), sine is 127. at 180 degrees (128 brads), sine is 0. at 270 degrees (192 brads), sine is -127. e ncoder : ncd s ine : sin all 2 all 2 all 2
basic stamp architecture ? sin, sqr page 108 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com figure 4.1: 127-unit circle to convert brads to degrees, multiply by 180 then divide by 128, or simply multiply with ?*/ 360?. to convert degr ees to brads, multiply by 128, then divide by 180. here?s a small program that demonstrates the sin and cos operators: degr var word brads var byte debug 2, 4, 0,"angle", tab, "cos", tab, "sin", cr debug "degrees", tab,"brads", tab, "(x)", tab,"(y)", cr for degr = 0 to 359 step 45 ' increment degrees brads = degr * 128 / 180 ' convert to brads debug cr, dec3 degr, tab, dec3 brads, tab ' display angle debug sdec cos brads, tab, sdec sin brads ' display cos & sin next the square root operator (sqr) comput es the integer square root of an unsigned 16-bit number. (the number must be unsigned since the square root of a negative number is an ?ima ginary? number.) remember that most square roots have a fractional part that the basic stamp discards when s quare r oot : sqr all 2
4: basic stamp architecture ? + basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 109 doing its integer-only math. so it comp utes the square root of 100 as 10 (correct), but the square root of 99 as 9 (the actual is close to 9.95). example: debug ? sqr 100 ' display square root of 100 (10) debug ? sqr 99 ' display of square root of 99 ' ...(9 due to truncation) table 4.6 lists the available bina ry (two-argument) operators. table 4.6: binary operators. note: some binary operators are not supported by all basic stamp models. operator description supported by: + addition all - subtraction all * multiplication all ** multiplication (returns upper 16-bits) all */ multiply by 8-bit integer, 8-bit fraction all bs2 models / division all // modulus (remainder of division) all atn returns arctangent of x/y vector all bs2 models hyp returns hypotenuse of x/y vector all bs2 models min limits a value to a specified low all max limits a value to a specified high all dig returns specified digit of number all bs2 models << shift bits left by specified amount all bs2 models >> shift bits right by specified amount all bs2 models rev reverse specified number of bits all bs2 models & bitwise and all | bitwise or all ^ bitwise xor all &/ logical and not bs1 only |/ logical or not bs1 only ^/ logical xor not bs1 only the addition operator (+) adds variables and/or constants, returning a 16- bit result. it works exactly as you wo uld expect with unsigned integers from 0 to 65535. if the result of addi tion is larger than 65535, the carry bit will be lost. if the values added are signed 16-bit numbers and the destination is a 16-bit variable, the result of the addition will be correct in both sign and value. a dd : + b inary o perators . 1 a ll 2
basic stamp architecture ? +, -, * page 110 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com for example: symbol value1 = w0 symbol value2 = w1 value1 = - 99 value2 = 100 value1 = value1 + value2 ' add the numbers debug value1 ' show the result (1) -- or -- value1 var word value2 var word value1 = - 1575 value2 = 976 value1 = value1 + value2 ' add the numbers debug sdec ? value1 ' show the result (-599) the subtraction operator (-) subtra cts variables and/or constants, returning a 16-bit result. it works exactly as you would expect with unsigned integers from 0 to 65535. if the result is negative, it will be correctly expressed as a signed 16-bit number. for example: symbol value1 = w0 symbol value2 = w1 value1 = 199 value2 = 100 value1 = value1 - value2 ' subtract the numbers debug value1 ' show the result (99) -- or -- value1 var word value2 var word value1 = 1000 value2 = 1999 value1 = value1 - value2 ' subtract the numbers debug sdec ? value1 ' show the result (-999) the multiply operator (*) multiplies variables and/or constants, returning the low 16 bits of the result. it wo rks exactly as you would expect with unsigned integers from 0 to 65535. if th e result of multiplication is larger than 65535, the excess bits will be lo st. multiplication of signed variables will be correct in both number and sign, provided that the result is in the range -32767 to +32767. s ubtract : - m ultiply : * 1 all 2 1 all 2 1 a ll 2 1 a ll 2
4: basic stamp architecture ? *, ** basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 111 symbol value1 = w0 symbol value2 = w1 value1 = 1000 value2 = 19 value1 = value1 * value2 ' multiply value1 by value2 debug value1 ' show the result (19000) -- or -- value1 var word value2 var word value1 = 1000 value2 = - 19 value1 = value1 * value2 ' multiply value1 by value2 debug sdec ? value1 ' show the result (-19000) the multiply high operator (**) multiplies variables and/or constants, returning the high 16 bits of the re sult. when you multiply two 16-bit values, the result can be as large as 32 bits. since the largest variable supported by pbasic is a word (16 bits), the highest 16 bits of a 32-bit multiplication result are normally lost. the ** (double-star) instruction gives you these upper 16 bits. for example, suppose you multiply 65000 ($fde8) by itself. the result is 4,225, 000,000 or $fbd46240. the * (star, or normal multiplication) instruction would return the lower 16 bits, $6240. the ** instruction returns $fbd4. symbol value1 = w0 symbol value2 = w1 value1 = $fde8 value2 = value1 ** value1 ' multiply $fde8 by itself debug $value2 ' return high 16 bits ($fbd4) -- or -- value1 var word value2 var word value1 = $fde8 value2 = value1 ** value1 ' multiply $fde8 by itself debug hex ? value2 ' return high 16 bits ($fbd4) an interesting application of the ** operator allows you no multiply a number by a fractional value less than one. the fraction must be expressed in units of 1/65536. to find the fractional ** argument, m ultiply h igh : ** 1 all 2 1 a ll 2 1 all 2
basic stamp architecture ? **, */ page 112 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com multiply the fraction part by 65536. for example, 0.72562 is represented by 47554, which is 0.72562 * 65536. symbol frac = 47554 ' = 0.72562 x 65536 symbol value = w0 value = 10000 value = value ** frac ' multiply 10000 by 0.72562 debug value ' show result (7256) -- or ? frac con 47554 ' = 0.72562 x 65536 value var word value = 10000 value = value ** frac ' multiply 10000 by 0.72562 debug ? value ' show result (7256) the multiply middle operator (*/) mu ltiplies variables and/or constants, returning the middle 16 bits of the 32 -bit result. this has the effect of multiplying a value by a whole number and a fraction. the whole number is the upper byte of the multiplier (0 to 255 whole units) and the fraction is the lower byte of the multiplier (0 to 255 units of 1/256 each). the */ (star- slash) instruction gives you an ex cellent workaround for the basic stamp's integer-only math. suppose you want to multiply a value by 1.5. the whole number, and therefore the u pper byte of the multiplier, would be 1, and the lower byte (fractional part) would be 128, since 128/256 = 0.5. it may be clearer to express the */ multiplier in hex?as $0180?since hex keeps the contents of the upper and lower bytes separate. here's an example: value1 var word value1 = 100 value1 = value1*/ $0180 ' multiply by 1.5 [1 + (128/256)] debug ? value1 ' show result (150) to calculate the constant for use with the */ operator, multiply the target (mixed) value by 256 and convert to an integer. for instance, take pi ( , 3.14159). the */ constant would be int(3.14159 * 256) = 804 ($0324). so the constant pi for use with */ would be $0324. this isn?t a perfect match for pi, but the error is only about 0.1%. note that the */ operator can be used to multiply by mixed va lues up to about 255.996. m ultiply m iddle : */ 1 all 2 all 2 all 2
4: basic stamp architecture ? /, // basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 113 the divide operator (/) divides variables and/or constants, returning a 16-bit result. works exactly as you wo uld expect with unsigned integers from 0 to 65535. use / only with positive values; signed values do not provide correct results. here?s an example of unsigned division: symbol value1 = w0 symbol value2 = w1 value1 = 1000 value2 = 5 value1 = value1 / value2 ' divide the numbers debug value1 ' show the result (200) -- or -- value1 var word value2 var word value1 = 1000 value2 = 5 value1 = value1 / value2 ' divide the numbers debug dec ? value1 ' show the result (200) a workaround to the inability to divi de signed numbers is to have your program divide absolute va lues, then negate the result if one (and only one) of the operands was negative. all values must lie within the range of -32767 to +32767. here is an example: sign var bit ' bit to hold the result sign value1 var word value2 var word value1 = 100 value2 = -3200 sign = value1.bit15 ^ value2.bit15 ' determine sign of result value2 = abs value2 / abs value1 ' divide absolute values if (sign = 1) then value2 = -value2 ' negate result if sign = 1 debug sdec ? value2 ' show the result (-32) the modulus operator (//) returns th e remainder left after dividing one value by another. some division pr oblems don?t have a whole-number result; they return a whole number and a fraction. for example, 1000/6 = 166.667. integer math doesn?t allow the fractional portion of the result, so 1000/6 = 166. however, 166 is an approximate answer, because 166*6 = 996. the division operation left a remainder of 4. the // (double-slash) d ivide : / m odulus : // 1 a ll 2 all 2 all 2 1 1 a ll 2
basic stamp architecture ? //, atn page 114 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com returns the remainder, 4 in this exam ple. naturally, nu mbers that divide evenly, such as 1000/5, produce a remainder of 0. example: symbol value1 = w0 symbol value2 = w1 value1 = 1000 value2 = 6 value1 = value1 // value2 ' get remainder of value1 / value2 debug value1 ' show the result (4) -- or -- value1 var word value2 var word value1 = 1000 value2 = 6 value1 = value1 // value2 ' get remainder of value1 / value2 debug ? value1 ' show the result (4) the arctangent operator (atn) return s the angle to the vector specified by x and y coordinate values. the syntax of atn is: xcoord atn ycoord where xcoord and ycoord are the coordinates of the target vector point. in the basic stamp, the angle is returned in binary radians (0 to 255) instead of degrees (0 to 359). see th e explanation of the sin operator for more information about binary radi ans. coordinate input values are limited to -127 to 127 (signed byte s) as shown in the diagram of the pbasic unit circle (figure 4.2). brads var word ' angle in brads degr var word ' angle in degrees brads = 4 atn 4 ' get angle degr = brads */ 360 ' convert to degrees debug sdec ? brads ' display brads (32) debug sdec ? degr ' display degrees (45) all 2 a rctangent : atn
4: basic stamp architecture ? atn, hyp, min basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 115 figure 4.2: atn and hyp operators in the pbasic unit circle the hypotenuse operator (hyp) returns the length of the hypotenuse of a right triangle with sides of length a and b. the syntax of hyp is: sidea hyp sideb where sidea and sideb are the side leng ths of a right-triangle (the order isn?t important). another application of hyp is to calculate the distance between the origin (0, 0) and a point (x, y) in a cartesian coordinate system. side length (vector) input values are limited to -127 to 127 (signed bytes). see diagram with atn operator, figure 4.2. debug ? 3 hyp 4 ' hypotenuse of 3x4 triangle (5) the minimum operator (min) limits a va lue to a specified 16-bit positive minimum. the syntax of min is: value min limit where value is a constant or variable va lue to perform the min function upon and limit is the minimum value that value is allowed to be. its logic is, ?if value is less than limit , then make result = limit ; if value is greater than or equal to limit , make result = value .? m inimum : min h ypotenuse : hyp all 2 1 a ll 2
basic stamp architecture ? min, max page 116 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com min works in positive math only; its comparisons are not valid when used on two?s complement negative numbers, since the positive-integer representation of a number like -1 ($ff ff or 65535 in unsigned decimal) is larger than that of a number like 10 ($000a or 10 decimal). use min only with unsigned integers. because of the way fixed-size integers work, you should be careful when using an expression involving min 0. for example, 0-1 min 0 will result in 65535 because of the way fixed-size integers wrap around. symbol value1 = w0 symbol value2 = w1 for value1 = 100 to 0 step -10 ' walk value1 from 100 to 0 value2 = value1 min 50 ' use min to clamp at 50 debug value2 ' show "clamped" value next -- or -- value var word for value = 100 to 0 step 10 ' walk value from 100 to 0 debug ? value min 50 ' show value1, use min to clamp at 50 next the maximum operator (max) limits a va lue to a specified 16-bit positive maximum. the syntax of max is: value max limit where value is a constant or variable va lue to perform the max function upon and limit is the maximum value that value is allowed to be. its logic is, ?if value is greater than limit , then make result = limit ; if value is less than or equal to limit , make result = value .? max works in positive math only; its comparisons are not valid when used on two?s complement negative numbers, since the positive-integer representation of a number like -1 ($ffff or 65535 in unsigned decimal) is larger than that of a number like 10 ($000a or 10 decimal). use max only with unsigned integers. because of the way fixed-size integers work, you should be careful when using an expression involving max 65535. for example, 65535+1 max 65535 will result in 0 because of the way fixed-size integers wrap around. 1 1 a ll 2 all 2 m aximum : max
4: basic stamp architecture ? max, dig, <<, >> basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 117 symbol value1 = w0 symbol value2 = w1 for value1 = 0 to 100 step 10 ' walk value1 from 0 to 100 value2 = value1 max 50 ' use max to clamp at 50 debug value2 ' show "clamped" value next -- or -- value var word for value = 0 to 100 step 10 ' walk value from 0 to 100 debug ? value max 50 ' show value, use max clamp at 50 next the digit operator (dig) returns the specified decimal digit of a 16-bit positive value. digits are numbered fr om 0 (the rightmost digit) to 4 (the leftmost digit of a 16-bit number; 0 to 65535). example: value var word idx var byte value = 9742 debug ? value dig 2 ' show digit 2 (7) for idx = 4 to 0 debug ? value dig idx ' show digits 0 through 4 (09742) next the shift left operator (<<) shifts the bits of a value to the left a specified number of places. bits shifted off the left end of a number are lost; bits shifted into the right end of the number are 0s. shifting the bits of a value left n number of times has the same effect as multiplying that number by 2 to the n th power. for instance 100 << 3 (shift the bits of the decimal number 100 left three places) is equivalent to 100 * 2 3 . here's an example: value var word idx var byte value = %1111111111111111 for idx = 1 to 16 ' repeat with idx = 1 to 16 debug bin16 ? value << idx ' shift value left idx places next the shift right operator (>>) shifts the bits of a value to the right a specified number of places. bits shif ted off the right end of a number are d igit : dig s hift l eft : << s hift r ight : >> all 2 1 all 2 all 2 all 2
basic stamp architecture ? >>, rev, &, | page 118 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com lost; bits shifted into the left end of th e number are 0s. shifting the bits of a value right n number of times has the same ef fect as dividing that number by 2 to the n th power. for instance 100 >> 3 (shift the bits of the decimal number 100 right three places) is equivalent to 100 / 2 3 . here's an example: value var word idx var byte value = %1111111111111111 for idx = 1 to 16 ' repeat with idx = 1 to 16 debug bin16 ? value >> idx ' shift value right idx places next the reverse operator (rev) returns a reversed (mirrored) copy of a specified number of bits of a value, st arting with the right-most bit (least significant bit or ?lsb?). for instance, %10101101 rev 4 would return %1011, a mirror image of the right-most four bits of the value. example: debug bin4 ? %10101101 rev 4 ' mirror 1st 4 bits (%1011) the and operator (&) returns the bitw ise and of two values. each bit of the values is subject to the following logic: 0 and 0 = 0 0 and 1 = 0 1 and 0 = 0 1 and 1 = 1 the result returned by & will contain 1s in only those bit positions in which both input values contain 1s. example: symbol value1 = b2 symbol value2 = b3 symbol result = b4 value1 = %00001111 value2 = %10101101 result = value1 & value2 debug %result ' show result of and (%00001101) -- or -- debug bin8 ? %00001111 & %10101101 ' show result of and (%00001101) the or operator (|) returns the bitwis e or of two values. each bit of the values is subject to the following logic: r everse : rev all 2 1 a ll 2 1 a ll 2 1 all 2 a nd : & o r : |
4: basic stamp architecture ? | , ^ basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 119 0 or 0 = 0 0 or 1 = 1 1 or 0 = 1 1 or 1 = 1 the result returned by | will contain 1s in any bit positions in which one or the other (or both) input values contain 1s. example: symbol value1 = b2 symbol value2 = b3 symbol result = b4 value1 = %00001111 value2 = %10101001 result = value1 | value2 debug %result ' show result of or (%10101111) -- or -- debug bin ? %00001111 | %10101001 ' show result of or (%10101111) the xor operator (^) returns the bitwis e xor of two values . each bit of the values is subject to the following logic: 0 xor 0 = 0 0 xor 1 = 1 1 xor 0 = 1 1 xor 1 = 0 the result returned by ^ will contain 1s in any bit positions in which one or the other (but not both) input values contain 1s. example: symbol value1 = b2 symbol value2 = b3 symbol result = b4 value1 = %00001111 value2 = %10101001 result = value1 ^ value2 debug %result ' show result or xor (%10100110) -- or -- x or : ^ all 2 1 1
basic stamp architecture ? &/, | / page 120 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com debug bin8 ? %00001111 ^ %10101001 ' show result of xor (%10100110) the and not operator (&/) returns the bitwise and not of two values. each bit of the values is subj ect to the following logic: 0 and not 0 = 0 0 and not 1 = 0 1 and not 0 = 1 1 and not 1 = 0 the result returned by &/ will contain 1s in any bit positions in which the first value is 1 and the second value is 0. example: symbol value1 = b2 symbol value2 = b3 symbol result = b4 value1 = %00001111 value2 = %10101001 result = value1 &/ value2 debug %result ' show result of and not (%00000110) the or not operator (|/) returns the bitwise or not of two values. each bit of the values is subject to the following logic: 0 or not 0 = 1 0 or not 1 = 0 1 or not 0 = 1 1 or not 1 = 1 the result returned by |/ will contain 1s in any bit positions in which the first value is 1 or the second value is 0. example: symbol value1 = b2 symbol value2 = b3 symbol result = b4 value1 = %00001111 value2 = %10101001 result = value1 |/ value2 debug %result ' show result of or not (%01011111) a nd n ot : &/ o r n ot : |/ all 2 1 1 1 1
4: basic stamp command reference ? ^/ basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 121 the xor not operator (^/) returns the bitwise xor not of two values. each bit of the values is subj ect to the following logic: 0 xor not 0 = 1 0 xor not 1 = 0 1 xor not 0 = 0 1 xor not 1 = 1 the result returned by ^/ will contain 1s in any bit positions in which the first value and second values are equal. example: symbol value1 = b2 symbol value2 = b3 symbol result = b4 value1 = %00001111 value2 = %10101001 result = value1 ^/ value2 debug %result ' show result of or not (%01011001) x or n ot : ^/ 1 1
basic stamp architecture page 122 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 123 introduction this chapter provides details on all three versions of the pbasic programming language. a categorical listing of all available pbasic commands is followed by an alph abetized command reference with syntax, functional descriptions, and example code for each command. pbasic language versions there are three forms of the pbasic language: pbasic 1.0 (for the bs1), pbasic 2.0 (for all bs2 models) and pbasic 2.5 (for all bs2 models). you may use any version of the language that is appropriate for your basic stamp module; however, when using any bs2 model, we suggest you use pbasic 2.5 for any new programs you write because of the advanced control and flexibility it allows. pbas ic 2.5 is backward compatible with almost every existing pbasic 2.0-based program, and code that is not 100% compatible can easily be modified to work in pbasic 2.5. this chapter gives details on every command for every basic stamp model. be sure to pay attention to any notes in the margins and body text regarding supported models and pbas ic language versions wherever they apply. the basic stamp editor for windows defaults to using pbasic 1.0 (for the bs1) or pbasic 2.0 (for all bs2 models). if you wish to use the default language for your basic stamp model yo u need not do anything special. if you wish to use pbasic 2.5, you must specify that fact, using the $pbasic directive in your source code, for example: ' {$pbasic 2.5} review the compiler directives section of chapter 3 for more details on this directive. note: you may also specify either 1.0 or 2.0 using the $pbasic directive if you wish to exp licitly state those desired languages. please note that the reserved word set will vary with each version of pbasic, with additional reserved wo rds for some basic stamp models. please see the reserved words tables in appendix b for the complete lists. pbasic 2.5 features many enhancements. table 5.1 gives a brief summary of these items, with references to more information given elsewhere.
basic stamp command reference page 124 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com feature categories new items description additional commands debugin, do...loop, exit, on. select...case allows easier user input and program control. see individual command descriptions. enhanced commands if...then, get, put, read, write improves program control, and spram and eeprom access. see individual command descriptions. additional directive pin provides flexible, cont ext-sensitive i/o pin references; see page 99. conditional compile directives #define, #error, #if...#then...#else, #select...case encourages development of source code that is compatible with multiple basic stamp models and helpful user hints; see page 70. additional predefined constants clrdn, clreol, crsrdn, crsrlf, crsrrt, crsrup, crsrx, crsrxy, crsry, lf symbols for control characters supported by the debug terminal. see table 5.13 in the debug command description, page 168. syntax enhancements , and : any line can be continued to the next line after the comma (,) character wherever commas are normally used. colons are required on label declarations. table 5.1: pbasic 2.5 enhancements. categorical listing of commands this section lists all available pbasic commands for all basic stamp models, grouped by category. co mmands with pbasic 2.5 enhanced syntax options are marked with (*); commands that exist only in pbasic 2.5 are indicated with ( 2.5 ). one or more of these icons indicates the item applies to the bs1, bs2, bs2e, bs2sx, bs2p, bs2pe, or bs2px respectively. if an item applies to all of the models in the bs2 family, this icon is used. b ranching / p rogram c ontrol branch jump to address specified by offset. if...then* conditionally execute one or more blocks of code. goto jump to address. gosub jump to subroutine at address. all 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2
5: basic stamp command reference basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 125 on 2.5 jump to address or subrouti ne specified by an offset. return return from subroutine. run switch execution to another program slot. pollrun switch execution to another program page upon the occurrence of a polled interrupt. select ?case 2.5 evaluate expression and conditionally execute a block of code based on comparison to multiple conditions. stop halt program execution until basic stamp is reset. l ooping s tructures do?loop 2.5 execute code block repetitively, with optional, conditional exit. exit 2.5 terminate execution of a looping code block (do...loop or for...next). for...next execute code block repetitively, a finite number of times using a counter. eeprom a ccess eeprom store data in eeprom during program download. data store data in eeprom during program download. read* read eeprom value into variable. write* write value into eeprom. store switch read/write access to different program slot. ram a ccess get* read scratch pad ram value into variable. put* write value into scratch pad ram. all 2 all 2 all 2 all 2 all 2 1 all 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2
basic stamp command reference page 126 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com n umerics let optional instruction to perform variable assignments. lookup look up data specified by offset and store in variable. this instruction provides a means to make a lookup table. lookdown find target?s matching value in table and store match number (0-n) in variable. random generate a pseudo-random number. d igital i/o configpin configure pin properties. input make pin an input. output make pin an output. reverse reverse direction of a pin. low make pin output low. high make pin output high. toggle make pin an output and toggle state. pulsin measure width of an input pulse. pulsout output a pulse by inverting a pin for a given amount of time. button debounce button, perform auto-repeat, and branch to address if button is in target state. count count cycles on a pin for a given amount of time. xout generate x-10 power line control codes. auxio switch control to auxiliary i/o pin group. mainio switch control to main i/o pin group. ioterm switch control to specified i/o pin group. pollin specify pin and state for a polled-interrupt. pollout specify pin and state for output upon a polled- interrupt. pollmode specify the polled-interrupt mode. 1 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2 all 2 all 2
5: basic stamp command reference basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 127 a synchronous s erial i/o serin input data in an asynchronous serial stream. serout output data in an asynchronous serial stream. owin input data from a 1-wire device. owout output data to a 1-wire device. s ynchronous s erial i/o shiftin shift data in from synchronous serial device. shiftout shift data out to synchronous serial device. i2cin input data from i 2 c serial device. i2cout output data to i 2 c serial device. p arallel i/o lcdcmd write a command to an lcd. lcdin read data from an lcd. lcdout write data to an lcd. a nalog i/o pwm output using pulse width modulation, then return pin to input. pot read a 5 k ? - 50 k ? potentiometer and scale result. rctime measure a variable resistance or capacitance. compare compare two 0-5 v analog voltages. t ime pause pause execution for 0?65535 milliseconds. pollwait pause until a polled-interrupt occurs. s ound sound generate tones or white noise. freqout generate one or two sine waves of specified frequencies. dtmfout generate dtmf telephone tones. all 2 all 2 all 2 1 1 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2
basic stamp command reference page 128 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com p ower c ontrol nap nap for a short period. power consumption is reduced. sleep sleep for 1-65535 seconds. power consumption is reduced. end sleep until the power cycles or the pc connects. power consumption is reduced. p rogram d ebugging debug send information to the pc for viewing in the debug terminal?s receive windowpane. debugin 2.5 retrieve information from the user via the pc, entered into the debug terminal?s transmit windowpane. syntax conventions bold upper case ? any word that appears bold with all capital letters must be typed exactly as shown. these are all reserved words. italics ? italicized words must be replaced with your content. [ ] ? square brackets must be typed, in the position shown around the given syntax element. only used with pbasic 2.0 and 2.5. ( ) ? parentheses must be typed in the position shown around the given syntax element; only used this way with pbasic 1.0.** { } ? curly braces indicate optional synt ax items. they are not typed as part of any syntax other than compiler directives. | ? vertical line separates mutually exclusive syntax elements. , \ # = ? where they appear, commas, backslashes, pound signs, and equal signs must be typed in the positions shown. **note: you may use parentheses to enclose expressions in pbasic 2.0 and 2.5, but they are not necessary. used within an expression, parentheses will change the order of evaluation. see page 103 for details and examples. all 2 1 a ll 2 1 a ll 2 1 a ll 2 1 a ll 2
5: basic stamp command reference ? auxio basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 129 auxio bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px auxio function switch from control of main i/o pins to auxiliary i/o pins (on the bs2p40 only). quick facts table 5.2: auxio quick facts. bs2p, bs2pe, and bs2px i/o pin ids 0 ? 15 (just like main i/o, but after auxio command, all references affect physical pins 21 ? 36). special notes the bs2p, bs2pe, and bs2px 24-pin modules accept this command, however, only the bs2p40 gives access to the auxiliary i/o pins. related commands mainio and ioterm explanation the bs2p, bs2pe, and bs2px are available as 24-pin modules that are pin compatible with the bs2, bs2e and bs2sx. also available is a 40-pin module called the bs2p40, with an additional 16 i/o pins (for a total of 32). the bs2p40's extra, or auxiliary, i/o pins can be accessed in the same manner as the main i/o pins (by using the ids 0 to 15) but only after issuing an auxio or ioterm command. the auxio command causes the basic stamp to affect the auxiliary i/o pins instead of the main i/o pins in all further code until th e mainio or ioterm command is reached, or the basic stamp is reset or power-cycled. auxio is also used when setting the dirs register for auxiliary i/o pins on the bs2p40. when the basic stamp module is reset, all ram variables including dirs and outs are cleared to zero. this affects both main and auxiliary i/o pins. on the bs2p24, bs2pe, and bs2px, the auxiliary i/o pins from the interpreter chip are not connected to physical i/o pins on the basic stamp module. while not connected to anything, these pins do have internal pull-up resistors activated, e ffectively connecting them to vdd. after reset, reading the auxiliary i/o from a bs2p24, bs2pe24, or bs2px24 will return all 1s.
auxio - basic stamp command reference page 130 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com here is a simple auxio example: high 0 ' make p0 high auxio ' select auxiliary pins low 0 ' make x0 low the first line of the above example will set i/o pin 0 of the main i/o pins (p0, physical pin 5) high. afterward, the auxio command tells the basic stamp that all commands following it should affect the auxiliary i/o pins. the following low command will set i/o pin 0 of the auxiliary i/o pins (x0, physical pin 21) low. note that the main i/o and auxiliar y i/o pins are independent of each other; the states of the main i/o pins remain unchanged while the program affects the auxiliary i/o pins, and vice versa. other commands that affect i/o group access are mainio and ioterm. demo program (aux_main_term.bsp) ' aux_main_term.bsp ' this program demonstrates the use of the auxio, mainio and ioterm ' commands to affect i/o pins in the auxiliary and main i/o groups. ' {$stamp bs2p} ' {$pbasic 2.5} #select $stamp #case bs2, bs2e, bs2sx #error "program requires bs2p40" #case bs2p, bs2pe, bs2px debug "note: this program designed for the bs2p40.", cr #endselect port var bit main: do mainio ' switch to main i/o pins toggle 0 ' toggle state of i/o pin p0 pwm 1, 100, 40 ' generate pwm on i/o pin p1 auxio ' switch to auxiliary i/o pins toggle 0 ' toggle state of i/o pin x0 pulsout 1, 1000 ' generate a pulse on i/o pin x1 pwm 2, 100, 40 ' generate pwm on i/o pin x2 a simple auxio example . m ain i/o and auxiliary i/o pins are independent and unaffected by changes in the opposite group . 2 p note: this example program will tokenize with the 24-pin bs2p , bs2pe, and bs2px, but its effects can only be seen on the bs2p40. this program uses conditional compilation techniques; see chapter 3 for more information.
5: basic stamp command reference ? auxio basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 131 ioterm port ' switch to main or aux i/os ' -- depending on port toggle 3 ' toggle state of i/o pin 3 ' -- on main and aux, alternately port = ~port ' invert port pause 1000 ' 1 second delay loop end
auxio - basic stamp command reference page 132 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? branch basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 133 branch bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px branch offset, ( address0, address1, ...addressn ) branch offset, [ address0, address1, ...addressn ] function go to the address specified by offset (if in range).  offset is a variable/constant/expression (0 ? 255) that specifies the index of the address, in the list, to branch to (0 ? n).  addresses are labels that specify where to go. branch will ignore any list entries beyond offset 255. quick facts table 5.3: branch quick facts. bs1 all bs2 models limit of address entries limited only by memory 256 related commands none on...goto explanation the branch instruction is useful when you want to write something like this: if value = 0 then case_0 ' when value is 0, jump to case_0 if value = 1 then case_1 ' when value is 1, jump to case_1 if value = 2 then case_2 ' when value is 2, jump to case_2 you can use branch to organize this into a single statement: branch value, [case_0, case_1, case_2] this works exactly the same as the previous if...then example. if the value isn?t in range (in this case if value is greater than 2), branch does nothing and the program continues with the next instruction after branch. branch can be teamed with the lookdown instruction to create a simplified select...case statement. see lookdown for an example. bs1 syntax not shown here. note: expressions are not allowed as arguments on the bs1. 1 all 2 1 1
branch ? basic stamp command reference page 134 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com demo program (branch.bs1) ' branch.bs1 ' this program shows how the value of idx controls the destination of the ' branch instruction. ' {$stamp bs1} ' {$pbasic 1.0} symbol idx = b2 main: debug "idx: ", #idx, " " branch idx, (task_0, task_1, task_2) ' branch to task debug "branch target error...", cr, cr ' ... unless out of range next_task: idx = idx + 1 // 4 ' force idx to be 0..3 goto main task_0: debug "branched to task_0", cr goto next_task task_1: debug "branched to task_1", cr goto next_task task_2: debug "branched to task_2", cr goto next_task demo program (branch.bs2) ' branch.bs2 ' this program shows how the value of idx controls the destination of the ' branch instruction. ' {$stamp bs2} ' {$pbasic 2.5} idx var nib main: debug "idx: ", dec1 idx, " " branch idx, [task_0, task_1, task_2] ' branch to task debug "branch target error...", cr, cr ' ... unless out of range next_task: idx = idx + 1 // 4 ' force idx to be 0..3 1 all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? branch basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 135 pause 250 goto main task_0: debug "branched to task_0", cr goto next_task task_1: debug "branched to task_1", cr goto next_task task_2: debug "branched to task_2", cr goto next_task
branch ? basic stamp command reference page 136 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? button basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 137 button bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px button pin, downstate, delay, rate, workspace, targetstate, address function monitor and process a pushbutton input, perform auto-repeat, and branch to address if button is in target state. button circuits may be active-low or active-high.  pin is a variable/constant/expression (0?15) that specifies the i/o pin to use. this pin will be set to input mode.  downstate is a variable/constant/expression (0 or 1) that specifies which logical state occurs when the button is pressed.  delay is a variable/constant/expression (0 ? 255) that specifies how long the button must be pressed be fore auto-repeat starts. the delay is measured in cycles of the button routine. delay has two special settings: 0 and 255. if delay is 0, button performs no debounce or auto-repeat. if delay is 255, button performs debounce, but no auto-repeat.  rate is a variable/constant/expression (0 ? 255) that specifies the number of cycles between auto-repeats. the rate is expressed in cycles of the button routine.  workspace is a byte variable used by button for workspace. it must be cleared to 0 before being used by button for the first time and should not be adjusted outside of the button command. note: all ram is cleared to 0 by default upon power-up or reset of the basic stamp module.  targetstate is a variable/constant/expression (0 or 1) that specifies which state the button should be in for a branch to occur. (0=not pressed, 1=pressed)  address is a label that specifies where to branch if the button is in the target state. explanation when you press a button or flip a switch, the contacts make or break a connection. a brief (1 to 20-ms) burst of noise occurs as the contacts scrape and bounce against each other. by scanning an input within a loop to note: expressions are not allowed as arguments on the bs1. the range of the pin argument on the bs1 is 0 ? 7. 1 1 a ll 2
button ? basic stamp command reference page 138 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com ensure that the contact remains in a specified state for a minimum duration, spurious multiple inputs caused by contact noise can be eliminated. the button instruction he lps prevent this noise from being interpreted as more than one switch action; this is the function of the delay parameter. for a demonstration of switch bounce, see the demo program for the count instruction. delay , combined with the rate argument, allows the programmer to control the rate at which multiple inputs are accepted by the basic stamp. button also lets pbasic react to a button press the way your computer keyboard does to a key press. when you press a key, a character immediately appears on the screen. if you hold the key down, there?s a delay, then a rapid-fire stream of characters appears on the screen. button?s auto-repeat function can be set up to work much the same way. button is designed for use inside a program loop. each time through the loop, button checks the state of the specified pin. when it first matches downstate, button begins the delay countdown for auto-repeat. then, in accordance with targetstate, it either branches to address (targetstate = 1) or doesn?t (targetstate = 0). if the switch stays in downstate, button counts the number of program loops that execute. when this count equals delay, button once again triggers the action specified by targetstate and address. hereafter, if the switch remains in downstate , button waits rate number of cycles between actions. the workspace variable is used by button to keep track of how many cycles have occurred since the pin switched to targetstate or since the last auto-repeat. button does not stop program execut ion. in order for its delay and auto-repeat functions to work proper ly, button must be executed from within a program loop.
5: basic stamp command reference ? button basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 139 figure 5.1: sample button circuits. active-high (left) and active-low (right). demo program (button.bs1) ' button.bs1 ' connect an active-low circuit to pin p0 of the bs1. when you press the ' button, the debug screen will display an asterisk (*). the program, as ' shown below, will print an asterisk at the first button press, then ' delay approximately one second (200 x 5 ms pause) before auto-repeating ' at a rate of approximately 100 ms (5 x 20 ms). feel free to modify the ' program to see the effects of your changes on the way button responds. ' {$stamp bs1} ' {$pbasic 1.0} symbol btn = 0 symbol btnwrk = b2 main: ' try changing the delay value (200) in button to see the effect of ' its modes: 0 = no delay; 1-254 = varying delays before auto-repeat; ' 255 = no auto-repeat (only one action per button press) ' ' the button instruction will cause the program to branch to ' no_press unless p0 = 0 pause 5 button btn, 0, 200, 20, btnwrk, 0, no_press debug "*" no_press: goto main 1
button ? basic stamp command reference page 140 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com demo program (button.bs2) ' button.bs2 ' connect an active-low circuit to pin p0 of the bs2. when you press the ' button, the debug screen will display an asterisk (*). the program, as ' shown below, will print an asterisk at the first button press, then ' delay approximately one second (200 x 5 ms pause) before auto-repeating ' at a rate of approximately 100 ms (5 x 20 ms). feel free to modify the ' program to see the effects of your changes on the way button responds. ' {$stamp bs2} ' {$pbasic 2.5} btn pin 0 btnwrk var byte main: ' try changing the delay value (200) in button to see the effect of ' its modes: 0 = no delay; 1-254 = varying delays before auto-repeat; ' 255 = no auto-repeat (only one action per button press) ' ' the button instruction will cause the program to branch to ' no_press unless p0 = 0 pause 5 button btn, 0, 200, 20, btnwrk, 0, no_press debug "*" no_press: goto main all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? compare basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 141 compare bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px compare mode, variable function enable or disable comparator, compare voltages on p1 and p2 and retrieve comparison result to store in variable.  mode is a variable/constant/expression (0 ? 2) that enables or disables the comparator (input pins p1 and p2) and determines if the optional comparator output pin (pin p0) is enabled or not. see table 5.4 for an explanation of the mode values.  variable is a variable (usually a bit) in which the comparison result is stored. quick facts table 5.4: compare quick facts. bs2px 0: disables comparato r 1: enables comparator with p0 as result output mode values 2: enables comparator without p0 as result output 0: voltage p1 > p2; p0 optionally outputs 0 variable values 1: voltage p1 < p2; p0 optionally outputs 1 explanation the compare command enables or di sables the built-in comparator hardware on the bs2px?s i/o pins p0, p1, and p2. i/o pins p1 and p2 are the comparator inputs and p0 is optionally the comparator result output pin. by default, the comparator feature is disabled. using the compare command with a mode argument of 1 or 2 enables the comparator feature (using input pins p1 and p2) and retu rns the result of the comparison in variable . if mode is 1, the result of the comparison is also output on i/o pin p0. the following is an example of the compare command: result var bit compare 1, result this example enables the comparator (se tting p0 to output the result, with p1 and p2 as the comparator inputs) and writes the result of the comparison into result . both result and the output pin p0 will be 0 if the
compare ? basic stamp command reference page 142 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com input voltage on p1 was greater than that of p2. result and the output pin p0 will be 1 if the input voltage on p1 was less than that of p2. note that the comparator hardware operates independently of the execution speed of the bs2px and will continue to run and update p0 if mode = 1, even during sleep mode (execution of end, nap, pollwait 8, or sleep commands). to avoid spurious current draw during sleep mode, disable the comparator first. demo program (compare.bpx) ' compare.bpx ' this example demonstrates the use of the compare command. ' connect two variable voltage sources (0 to 5 volts) on i/o pins ' p1 and p2 (or a button on each pin connected to ground). run the program ' and watch the debug terminal display as you adjust the variable voltage ' or press the buttons. ' {$stamp bs2px} ' {$pbasic 2.5} result var bit #if $stamp <> bs2px #then #error "this program requires a bs2px." #endif setup: configpin direction, %0000000000000001 'p0 = output, all others = input configpin pullup, %0000000000000110 'enable pull-ups on p1 and p2 debug "bs2px comparator demonstration", cr, "==============================", cr, "input voltage: p1 > p2", cr, "output state: p0 = 0" main: do 'display p1/p2 comparison compare 1, result if result = 0 then debug crsrxy,18,2,">" else debug crsrxy,18,2,"<" endif debug crsrxy,20,3,bin1 result loop note: this example program can be used only with the bs2px.
5: basic stamp command reference ? configpin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 143 configpin bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px configpin mode, pinmask function configure special properties of i/o pins.  mode is a variable/constant/expression (0 ? 3), or one of four predefined symbols, that specifies the i/o pin property to configure: schmitt trigger, logic threshold, pull-up resistor or output direction. see table 5.5 for an explanation of mode values.  pinmask is a variable/constant/expression (1 ? 65535) that indicates how mode is applied to i/o pins. each bit of pinmask corresponds to an individual i/o pin. a high bit (1) enables the mode and a low bit (0) disables the mode on the corresponding i/o pin. quick facts table 5.5: configpin quick facts. bs2px 0 (or schmitt): schmitt trigger 1 (or threshold): logic threshold 2 (or pullup): pull-up resistor mode values 3 (or direction): output direction related commands (for direction mode) input and output, and the dirx = # assignment statement explanation the configpin command enables or di sables special i/o pin properties on all 16 i/o pins at once. there are four properties, or modes, available: schmitt trigger, logic threshold, pull-up resistor, and output direction. each i/o pin on the bs2px contains sp ecial hardware dedicated to each of these properties. by default, all basic stamp i/o pins are set to inputs. enabling the output direction mode sets an i/o pi n?s direction to output. disabling the output direction mode sets an i/o pin?s direction to input. this has the same effect as using the output or input commands, or the dirx = # assignment statement to configure i/o pin directions. the following is an example of the co nfigpin command using the output direction mode: configpin direction, %0000000100010011 o utput d irection .
configpin ? basic stamp command reference page 144 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com every high bit (1) in the pinmask argument enables the output direction for the corresponding i/o pin while ev ery low bit (0) disables the output direction. in the above example, i/o pins 8, 4, 1, and 0 are set to the output direction and all other i/o pins are set to the input direction. this is similar to the following statement: dirs = %0000000100010011 pull-up resistors are commonly used in circuitry where a component, such as a button, provides an open/drain signal; the signal is either floating (open) or is driven to ground (drain). since the basic stamp input pins must always be connected to either 5 volts or ground (0 volts) in order to read a reliable logic state with them, a pull-up resistor is required on circuitry, such as the bu tton circuit mentioned above, so that the signal is never left floating (electrically disconnected). the following example enables internal pull-up resistors on i/o pins 15, 12, 6, and 3, and disables internal pull-up resistors on all other i/o pins: configpin pullup, %1001000001001000 note that the internal pull-up resist ors are intentionally weak, about 20 k ? . additionally, the internal pull-u p resistors can be activated for all pins, regardless of pin direction, but really matter only when the associated pin is set to input mode. an input pin?s logic threshold determines the voltage levels that are interpreted as logic high (1) and logic low (0). most microcontrollers, and other integrated circuits use one of tw o types of logic threshold: ttl level or cmos level. the basic stamp i/o pins are, by default, configured for ttl level logic thresholds. figure 5.2 is an illustration of the difference between ttl and cmos logic levels. ttl logic level cmos logic level figure 5.2: ttl and cmos logic level threshold voltages p ull - up r esistors . l ogic t hreshold .
5: basic stamp command reference ? configpin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 145 the logic threshold for ttl is 1.4 volts; a voltage below 1.4 is considered to be a logic 0 while a voltage above 1.4 is considered to be a logic 1. the logic threshold for cmos is 50% of vdd; a voltage below ? vdd is considered a logic 0 while a voltage above ? vdd is considered a logic 1. for the configpin command?s threshold mode, a high bit (1) in the pinmask argument sets the correspondi ng i/o pin to cmos threshold level, and a low bit sets it to a ttl threshold level. the following example sets cmos threshold level on i/o pins 3, 2, 1, and 0, and ttl threshold level on all other i/o pins. configpin threshold, %0000000000001111 the threshold level can be set for all pins, regardless of pin direction, but really matters only when the asso ciated pin is set to input mode. normally, if a signal on an input pin is somewhat noisy (the voltage level randomly rises and falls beyond the logic threshold boundary) then reading that pin?s input value will re sult in spurious highs and lows (1s and 0s). schmitt triggers are circuits that make inputs more steady and reliable by adding a region of hyster esis around the logic threshold that the signal must completely traverse before the logic level is interpreted as being changed. by default basic stam p i/o pins are set to normal input mode, but the bs2px can be configured for schmitt trigger mode as well. figure 5.3 illustrates schmitt trigger characteristics. figure 5.3: schmitt trigger characteristics in schmitt trigger mode, the threshold for a logic 0 is approximately 15% of vdd and the threshold for a logic 1 is approximately 85% of vdd. the input pin defaults to an unknown state until the initial voltage crosses a logic 0 or logic 1 boundary. thereafter, the voltage must cross above 85% of vdd to be interpreted as a logic 1 and must cross below 15% of vdd to be interpreted as a logic 0. if the voltage transitions somewhere between the two thresholds, the interpreted lo gic state remains the same as the previous state. s chmitt t rigger
configpin ? basic stamp command reference page 146 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com for the configpin command?s schmitt mode, a high bit (1) in the pinmask argument enables the schmitt trigger on the corresponding i/o pin and a low bit (0) disables the schm itt trigger. the following example sets schmitt triggers on i/o pins 7, 6, 5, and 4, and sets all other i/o pins to normal mode. configpin schmitt, %0000000011110000 schmitt trigger mode can be activate d for all pins, regardless of pin direction, but really matters only when the associated pin is set to input mode. demo program (configpin.bpx) ' configpin.bpx ' this example demonstrates the use of the configpin command. ' all i/o pins are set to inputs with various combinations of ' pull-up resistor, logic threshold and schmitt-trigger properties. ' while running, this program will constantly display the state of all ' input pins along with an indication of the configuration for each group ' of pins. try connecting different input signals to the i/o pins (such as ' buttons, a function generator with a slowing sweeping signal (0 to 5 ' vdc)) or simply running your fingers across the i/o pins and note how ' they react based upon their configured property. ' {$stamp bs2px} ' {$pbasic 2.5} #if $stamp <> bs2px #then #error "this program requires a bs2px." #endif setup: configpin direction, %0000000000000000 'set all i/o pins to inputs configpin pullup, %1111111111110000 'enable pull-ups on pins 4 - 15 configpin threshold, %0000111100000000 'set p8-p11 to cmos, others ttl configpin schmitt, %1111000000000000 'enable schmitt-triggers p12-p15 debug cls debug " bs2px input pin configuration test", cr, "=========================================================", cr, " p15-p12: pull-up resistors, ttl & schmitt-triggers", cr, " /", cr, " / p11-p8: pull-up resistors & cmos", cr, " / /", cr, " | / p7-p4: pull-up resistors & ttl", cr, " | | /", cr, " | | | p3-p0: normal", cr, " | | | /", cr, note: this example program can be used only with the bs2px.
5: basic stamp command reference ? configpin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 147 " | | | |", cr, "---- ---- ---- ----" main: do 'display input pin states debug crsrxy,0,12, bin4 ind, " ", bin4 inc, " ", bin4 inb, " ", bin4 ina loop
configpin ? basic stamp command reference page 148 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? count basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 149 count bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px count pin, duration, variable function count the number of cycles (0-1-0 or 1-0-1) on the specified pin during the duration time frame and store that number in variable.  pin is a variable/constant/expression (0 ? 15) that specifies the i/o pin to use. this pin will be set to input mode.  duration is a variable/constant/expression (1 ? 65535) specifying the time during which to count. the unit of time for duration is described in table 5.6.  variable is a variable (usually a word) in which the count will be stored. quick facts table 5.6: count quick facts. note: all timing values are approximate. bs2, bs2e bs2sx bs2p bs2pe bs2px units in duration 1 ms 400 s 287 s 720 s 287 s duration range 1 ms to 65.535 s 400 s to 26.214 s 287 s to 18.809 s 720 s to 47.18 s 287 s to 18.809 s minimum pulse width 4.16 s 1.66 s 1.20 s 3.0 s 1.20 s maximum frequency (square wave) 120,000 hz 300,000 hz 416,700 hz 166,667 hz 416,700 hz related command pulsin explanation the count instruction makes the pin an input, then for the specified duration of time, counts cycles on that pin and stores the total in variable . a cycle is a change in state from 1 to 0 to 1, or from 0 to 1 to 0. according to table 5.6, count on the bs2 can respond to transitions (pulse widths) as small as 4.16 microseconds (s). a cycle consists of two transitions (e.g., 0 to 1, then 1 to 0), so count (on the bs2) can respond to square waves with periods as short as 8.32 s; up to 120 kilohertz (khz) in frequency. for non-square waves (those whose high time and low time are unequal), the shorter of the high and low times must be at least 4.16 s in all 2
count ? basic stamp command reference page 150 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com width (on the bs2). refer to table 5.6 for data on other basic stamp models. if you use count on slowly changing analog waveforms like sine waves, you may find that the value returned is higher than expected. this is because the waveform may pass thro ugh the basic stamp module?s logic threshold slowly enough that noise caus es false counts. you can fix this by passing the signal through a schmitt trigger, like one of the inverters of a 74hct14. or, you may use the bs2p x?s built-in schm itt-trigger pin property; see the configpin section be ginning on page 143 for details. demo program (count.bs2) ' count.bs2 ' connect an active-low button circuit shown in the button command ' description to pin p0 of the bs2. the debug screen will prompt you to ' press the button as quickly as possible for a 1-second count. when the ' count is done, the screen will display your "score," the total number of ' cycles registered by count. note that this score will almost always ' be greater than the actual number of presses because of switch contact ' bounce. ' {$stamp bs2} ' {$pbasic 2.5} pushbtn pin 0 ' pushbutton on p0 #select $stamp #case bs2, bs2e duradj con $100 ' / 1 #case bs2sx duradj con $280 ' / 0.400 #case bs2p, bs2px duradj con $37b ' / 0.287 #case bs2pe duradj con $163 ' / 0.720 #endselect capture con 1000 ' 1 second cycles var word ' counted cycles main: do debug cls, "how many times can you press the button in 1 second?", cr pause 1000 debug "ready, set... " all 2 note: this example program can be used with all bs2 models. this program uses conditional compilation techniques; see chapter 3 for more information.
5: basic stamp command reference ? count basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 151 pause 500 debug "go!", cr count pushbtn, (capture */ duradj), cycles debug cr, "your score: ", dec cycles, cr pause 3000 debug "press button to go again." do : loop until (pushbtn = 0) ' wait for button press loop end
count ? basic stamp command reference page 152 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? data basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 153 data bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px (see eeprom ) { symbol } data dataitem { , dataitem? } function write data to the eeprom during program download.  symbol is an optional, unique sy mbol name that will be automatically defined as a constant equal to the location number of the first data item.  dataitem is a constant/expression (0 ? 65535) indicating a value, and optionally how to store the value. quick facts table 5.7: data quick facts. all bs2 models special notes writes values to eeprom during download in blocks of 16 bytes. writes byte or word-sized values. can be used to decrease program size. related commands read and write explanation when you download a program into the basic stamp, it is stored in the eeprom starting at the highest address (2047) and working towards the lowest address. most programs don?t use the entire eeprom, so the lower portion is available for other uses. the data directive allows you to define a set of data to store in the available eeprom locations. it is called a ?directive? rather than a ?command? because it performs an activity at compile-time rather than at run-time (i.e.: the data directive is not downloaded to the basic stamp, but the data it contains is downloaded). the simplest form of the data directive is something like the following: data 100, 200, 52, 45 this example, when downloaded, will cause the values 100, 200, 52 and 45 to be written to eeprom locations 0, 1, 2 and 3, respectively. you can then use the read and write commands in your code to access these locations and the data you?ve stored there. w riting simple , sequential data . 1 all 2
data ? basic stamp command reference page 154 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com data uses a counter, called a pointer, to keep track of available eeprom addresses. the value of the pointer is initially 0. when a program is downloaded, the data directive stores the first byte value at the current pointer address, then increments (adds 1 to) the pointer. if the program contains more than one data directiv e, subsequent datas start with the pointer value left by the previous data. for example, if the program contains: data 72, 69, 76, 76, 79 data 104, 101, 108, 108, 111 the first data directive will start at location 0 and increment the pointer for each data value it stores (1, 2, 3, 4 and 5). the second data directive will start with the pointer value of 5 and work upward from there. as a result, the first 10 bytes of eeprom will look like the following: eeprom location (address) 0 1 2 3 4 5 6 7 8 9 contents 72 69 76 76 79 104 101 108 108 111 table 5.8: example eeprom storage. what if you don?t want to store values starting at location 0? fortunately, the data directive has an option to sp ecify the next location to use. you can specify the next location number (to set the pointer to) by inserting a dataitem in the form @x ;where x is the location number. the following code writes the same data in table 5.8 to locations 100 through 109: data @100, 72, 69, 76, 76, 79, 104, 101, 108, 108, 111 in this example, the first dataitem is @100. this tells the data directive to store the following dataitem(s) starting at location 100. all the dataitems to the right of the @100 are stored in their respective locations (100, 101, 102? 109). in addition, the data directive al lows you to specify new starting locations at any time within the dataitem list. if, for example, you wanted to store 56 at location 100 and 47 at location 150 (while leaving every other location intact), you could type the following: data @100, 56, @150, 47 if you have multiple data directives in your program, it may be difficult to remember exactly what locations contain the desired data. for this reason, the data directive can optionally be prefixed with a unique t he data pointer ( counter ). w riting data to other locations . a utomatic constants for defined data .
5: basic stamp command reference ? data basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 155 symbol name. this symbol becomes a constant that is set equal to the location number of the firs t byte of data within the directive. for example, mynumbers data @100, 72, 73 this would store the values 72 and 73 starting with location 100 and will create a constant, called mynumbers , which is set equal to 100. your program can then use the mynumbers constant as a reference to the start of the data within a read or write command. each data directive can have a unique symbol preceding it, allowing you to reference the data defined at different locations. there may be a time when you wish to reserve a section of eeprom for use by your basic code, but not necessar ily store data there to begin with. to do this, simply specify a dataitem within parentheses, as in: data @100, (20) the above data directive will reserve 20 bytes of eeprom, starting with location 100. it doesn?t store any valu es there, rather it simply leaves the data as it is and increments data?s location pointer by 20. a good reason to do this is when you have a program already downloaded into the basic stamp that has created or mani pulated some data in eeprom. to protect that section of eeprom from being overwritten by your next program (perhaps a new version of th e same program) you can reserve the space as shown above. the eeprom?s contents from locations 100 to 119 will remain intact. note: this only "reserves" the space for the program you are currently downloading; the basic stamp does not know to "reserve" the space for future programs. in other words, make sure use this feature of the data directive in every program you download if you don't want to risk overwriting valuable eeprom data. it is important to realize that eeprom is not overwritten during programming unless it is needed for program storage, or is filled by a data directive specifying data to be written. during downloading, eeprom is always written in 16-byte sections if, and only if, any location within that section needs writing. data can also store the same number in a block of consecutive locations. this is similar to reserving a block of eeprom, above, but with a value added before the first parenthesis. r eserving eeprom locations . w riting a block of the same value . i mportant concept : h ow data and programs are downloaded into eepr o m.
data ? basic stamp command reference page 156 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com for example, data @100, 0 (20) this statement writes the value 0 in all the eeprom locations from 100 to 119. a common use for data is to store strings; sequences of bytes representing text. pbasic converts quoted text like "a" into the corresponding ascii character code (65 in this case). to make data entry easier, you can place quotes around a whole chunk of text used in a data directive, and pbasic will understand it to mean a series of bytes (see the last line of code below). the following three data directives are equivalent: data 72, 69, 76, 76, 79 data "h", "e", "l", "l", "o" data "hello" all three lines of code, above, will result in the numbers 72, 69, 76, 76, and 79 being stored into eeprom upon downloading. these numbers are simply the ascii character codes for "h", "e", "l", "l", and "o", respectively. see the demo program, below, for an example of storing and reading multiple text strings. the eeprom is organized as a sequential set of byte-sized memory locations. by default, the data dire ctive stores bytes into eeprom. if you try to store a word-sized value (ex: data 1125) only the lower byte of the value will be stored. this do es not mean that you can't store word- sized values, however. a word consis ts of two bytes, called a low-byte and a high-byte. if you wanted to store the value 1125 using the data directive, simply insert the prefix "word" before the number, as in: data word 1125 the directive above will automaticall y break the word-sized value into two bytes and store them into two se quential eeprom locations (the low- byte first, followed by the high-byte). in this case, the low-byte is 101 and the high byte is 4 and they will be stored in locations 0 and 1, respectively. if you have multiple word-sized values, you must prefix each value with "word", as in: data word 1125, word 2000 w riting text strings . w riting word values vs . byte values .
5: basic stamp command reference ? data basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 157 to retrieve a word-sized value, you'll need to use the word modifier in the read command and a word-sized variable. finally, a dataitem may be defined using a simple expression with the binary operators shown in table 4.5. for example, minlvl con 10 mylvl var byte level1 data minlvl + 10 level2 data minlvl * 5 + 21 read level2, mylvl ' read ee location level2 debug dec mylvl ' show value of mylvl (71) demo program (data.bs2) ' data.bs2 ' this program stores a number of large text strings into eeprom with the ' data directive and then sends them, one character at a time via the debug ' command. this is a good demonstration of how to save program space by ' storing large amounts of data in eeprom directly, rather than embedding ' the data into debug commands. ' {$stamp bs2} ' {$pbasic 2.5} idx var word ' current location number phrase var nib ' current phrase number char var byte ' character to print ' ----- define all text phrases (out of order, just for fun!) ----- ' text1 data "here is the first part of a large chunk of textual " data "data ", cr, "that needs to be transmitted. there's " data "a 5 second delay", cr, "between text paragraphs. ", cr data cr, 0 text3 data "the alternative (having multiple debugs or serouts, " data "each ", cr, "with their own line of text) consumes " data "much more eeprom ", cr, "(program) space. ", cr data cr, 0 text6 data "the 0 is used by this program to indicate we've " data "reached the ", cr, "end of text. the main routine " data "pauses in between each block of", cr, "text,and then " data "uses a lookup command to retrieve the location ", cr data "of the next desired block of text to print. ", 0 all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
data ? basic stamp command reference page 158 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com text4 data cls, "this program also demonstrates retrieving data " data "out of order ", cr, "in relation to the way it is " data "stored in eeprom. additionally,", cr, "control codes " data "(like carriage-returns, clear-screens, etc) can ", cr data "be embedded right in the data, as it is here. ", cr data cr, 0 text2 data "this is an example of a good way to save space in " data "your ", cr, "basic stamp's program by storing data " data "into eeprom and ", cr, "retrieving it, one byte at a " data "time, and transmitting it ", cr, "with just a single " data "debug (or serout) command.", cr, cr, 0 text5 data "the print_it routine simply takes the idx variable, " data "retrieves", cr, "the character at the eeprom location " data "pointed to by it, and ", cr, "prints it to the screen " data "until it finds a byte with a value of 0.", cr, cr, 0 main: debug cls ' clear debug window for phrase = 1 to 6 ' print blocks one by one lookup (phrase - 1), [text1, text2, text3, text4, text5, text6], idx gosub print_it pause 5000 ' pause for 5 seconds next end print_it: do read idx, char ' get next character idx = idx + 1 ' point to next location if (char = 0) then exit ' if 0, we're done with block debug char ' otherwise, transmit it loop return ' return to the main routine
5: basic stamp command reference ? debug basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 159 debug bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px debug outputdata { , outputdata } function display information on the pc screen within the basic stamp editor?s debug terminal. this command can be used to display text or numbers in various formats on the pc screen in order to follow program flow (called debugging) or as part of the functionality of the basic stamp application.  outputdata is a variable/constant/expression (0 ? 65535) that specifies the information to outp ut. valid data can be ascii characters (text strings and control characters), decimal numbers (0 - 65535), hexadecimal numbers ($0000 - $ffff) or binary numbers (up to %1111111111111111). data can be modified with special formatters as explained below. quick facts table 5.9: debug quick facts. bs1 bs2, bs2e, bs2sx bs2p, bs2pe bs2px serial protocol asynchronous 4800, n, 8, 1 true polarity custom packetized format asynchronous 9600, n, 8, 1 inverted polarity raw data asynchronous 19200, n, 8, 1 inverted polarity raw data related commands none serout and debugin explanation debug provides a convenient way for your basic stamp to send messages to the pc screen while running. the name ?debug? suggests its most popular use; debugging progra ms by showing you the value of a variable or expression, or by indica ting what portion of a program is currently executing. debug is also a great way to rehearse programming techniques. throughout this manual, we use debug to give you immediate feedback on the effects of instructions. the following example demonstrates using the debug command to send the text string message ?hello world!?. debug "hello, world!" after you download this one-line program, the basic stamp editor will open a debug terminal on your pc screen and wait for a response from note: expressions are not allowed as arguments on the bs1. the only constant allowed for the bs1 debug command is a text string. 1 1 a ll 2
debug ? basic stamp command reference page 160 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the basic stamp. a moment later, th e phrase "hello world!" will appear. note that if you close the debug terminal, your program keeps executing, but you can?t see the debug data anymore. multiple pieces of data can be sent with one debug command by separating the data with commas (,). the following example produces exactly the same results as the example above. debug "hello ", "world!" debug can also print and format numbers (values) from both constants and variables. the formatting methods for debug are very different for the bs1, than for any other basic stamp. please read the appropriate sections, below, carefully. basic stamp 1 formatting on the bs1, the debug command, by default, displays numbers in the format "symbol = value" (followed by a carriage return), using the decimal number system. for example, symbol x = b2 x = 75 debug x displays "x = 75" on the screen. to display the value, in decimal, without the "x =" text, use the value formatter (#) before the variable name. for example, the following code displays "75" on the screen. symbol x = b2 x = 75 debug #x to display numbers in hexadecimal or binary form, use the $ or % formatter, respectively. the code below displays the same number in its hexadecimal and binary forms. symbol x = b2 x = 75 debug $x, %x d isplaying decimal numbers (bs1). d isplaying hexadecimal or binary numbers ( bs1 ) . 1
5: basic stamp command reference ? debug basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 161 after running the above code, "x = $4b" and "x = %01001011" should appear on the screen. to display hexadecimal or binary values without the "symbol = " preface, use the value formatter (#) before the $ and %, as shown below: symbol x = b2 x = 75 debug #x, "as hex is ", #$x ' displays "75 as hex is $4b" debug #x, "as binary is ", #%x ' displays "75 as binary is %01001011" to display a number as its ascii character equivalent, use the ascii formatter (@). symbol x = b2 x = 75 debug @x table 5.10: debug formatters for the basic stamp 1. formatter description # suppresses the "symbol = x" format and displays only the 'x' value. the default format is decimal but may be combined with any of the formatters below (ex: #x to display: x value) @ displays "symbol = 'x'" + carriage return; where x is an ascii character. $ hexadecimal text. % binary text. two pre-defined symbols, cr and cls, can be used to send a carriage- return or clear-screen command to the debug terminal. the cr symbol will cause the debug terminal to start a new line and the cls symbol will cause the debug terminal to clear itself and place the cursor at the top-left corner of the screen. the following code demonstrates this. debug "you can not see this.", cls, "here is line 1", cr, "here is line 2" when the above is run, the final result is "here is line 1" on the first line of the screen and "here is line 2" on the second line. you may or may not have seen "you can not see this." appear first. this is because it was immediately followed by a clear-scre en symbol, cls, which caused the display to clear the screen before displaying the rest of the information. note: the rest of this discussion does not apply to the basic stamp 1. u sing cr and cls (bs1). d isplaying ascii c haracters (bs1).
debug ? basic stamp command reference page 162 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com basic stamp 2, 2e, 2sx, 2p, 2pe, and 2px formatting on the all basic stamp models except the bs1, the debug command, by default, displays everything as ascii characters. what if you want to display a number? you might think th e following example would do this: x var byte x = 65 debug x ' try to show decimal value of x since we set x equal to 65 (in line 2), you might expect the debug line to display ?65? on the screen. instead of ?65?, however, you?ll see the letter ?a? if you run this example. the problem is that we never told the basic stamp how to output x, and it defaults to asc ii (the ascii character at position 65 is ?a?). instead, we need to tell it to display the ?decimal form? of the number in x. we can do this by using the decimal formatter (dec) before the variable. the exam ple below will display ?65? on the screen. x var byte x = 65 debug dec x ' show decimal value of x in addition to decimal (dec), debug can display numbers in hexadecimal (hex) and binary (bin). see table 5.11 and table 5.12 for a complete list of formatters. expressions are allowed within the debug command arguments as well. in the above code, debug dec x+ 25 would yield "90" and debug dec x*10/2-3 would yield "322". d isplaying ascii characters . d isplaying decimal numbers . all 2 d isplaying hexadecimal and binary numbers . e xpressions in debug commands .
5: basic stamp command reference ? debug basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 163 table 5.11: debug special formatters for all bs2 models. special formatter action ? displays "symbol = x' + carriage return; where x is a number. default format is decimal, but may be combined with conversion formatters (ex: bin ? x to display "x = binary_number"). asc ? displays "symbol = 'x'" + ca rriage return; where x is an ascii character. str bytearray {\l} send character string from an array. the optional \l argument can be used to limit the output to l characters, otherwise, characters will be sent up to the first byte equal to 0 or the end of ram space is reached. rep byte \l send a string consisting of byte repeated l times (ex: rep "x"\10 sends "xxxxxxxxxx"). table 5.12: debug conversion formatters for all bs2 models. conversion formatter type of number notes dec{1..5} decimal, optionally fixed to 1 ? 5 digits 1 sdec{1..5} signed decimal, optionally fixed to 1 ? 5 digits 1,2 hex{1..4} hexadecimal, optionally fixed to 1 ? 4 digits 1,3 shex{1..4} signed hexadecimal, optionally fixed to 1 ? 4 digits 1,2 ihex{1..4} indicated hexadecimal, optionally fixed to 1 ? 4 digits ($ prefix) 1 ishex{1..4} signed, indicated hexadecimal, opti onally fixed to 1 ? 4 digits ($ prefix) 1,2 bin{1..16} binary, optionally fixed to 1 ? 16 digits 1 sbin{1..16} signed binary, optionally fixed to 1 ? 16 digits 1,2 ibin{1..16} indicated binary, optionally fixed to 1 ? 16 digits (% prefix) 1 isbin{1..16} signed, indicated binary, optiona lly fixed to 1 ? 16 digits (% prefix) 1,2 1 fixed-digit formatters like dec4 will pad t he number with leading 0s if necessary; ex: dec4 65 sends 0065. if a number is larg er than the specified number of digits, the leading digits will be dropped; ex: dec4 56422 sends 6422. 2 signed modifiers work under two's complement rules. 3 the hex modifier can be used for bcd to decimal conversion. see ?hex to bcd conversion? on page 97. as seen in table 5.12, special versions of the dec, hex and bin formatters allow for the display of indicated, signed and fixed-width numbers. the term "indicated" simp ly means that a special symbol is displayed, before the number, indicating what number system it belongs to. for example, x var byte x = 65 debug hex x ' show hexadecimal value of x displays "41" (65, in decimal, is 41, in hexadecimal). you might see a problem here? unless you knew the number was supposed to be d isplaying " indicated " numbers .
debug ? basic stamp command reference page 164 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com hexadecimal, you might think it was 41, in decimal? a totally different number. to help avoid this, use the ihex formatter (the "i" stands for indicated). changing the debug line to read: debug ihex x would print "$41" on the screen. a similar fo rmatter for binary also exists, ibin, which prints a "%" before the number. signed numbers are preceded with a space ( ) or a minus sign (-) to indicate a positive or negative number, respectively. normally, any number displayed by the basic stamp is shown in its unsigned (positive) form without any indicator. the sign ed formatters allow you to display the number as a signed (rather than unsigned) value. note: only word- sized variables can be used for signed number display. the code below demonstrates the difference in all three numbering schemes. x var word x = -65 debug "signed: ", sdec x, " ", ishex x, " ", isbin x, cr debug "unsigned: ", dec x, " ", ihex x, " ", ibin x this code will generate the display shown below: signed: -65 -$41 -%1000001 unsigned: 65471 $ffbf %1111111110111111 the signed form of the number ?65 is shown in decimal, hexadecimal and then in binary on the top line. the unsigned form, in all three number systems, is shown on the bottom line. if the unsigned form looks strange to you, it's because negative numb ers are stored in twos complement format within the basic stamp. suppose that your program contai ned several debug instructions showing the contents of different vari ables. you would want some way to tell them apart. one possible way is to do the following: x var byte y var byte x = 100 y = 250 debug "x = ", dec x, cr ' show decimal value of x debug "y = ", dec y, cr ' show decimal value of y d isplaying signed vs . unsigned numbers . a utomatic names in the display .
5: basic stamp command reference ? debug basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 165 but typing the name of the variables in quotes (for the display) can get a little tedious. a special formatter, the question mark (?), can save you a lot of time. the code below does exactl y the same thing (with less typing): x var byte y var byte x = 100 y = 250 debug dec ? x ' show decimal value of x debug dec ? y ' show decimal value of y the display would look something like this: x = 100 y = 250 the ? formatter always displays data in the form "symbol = value" (followed by a carriage return). in addition, it defaults to displaying in decimal, so we really only needed to type: debug ? x for the above code. you can, of course, use any of the three number systems. for example: debug hex ? x or debug bin ? y. it's important to note that the "symbol" it displays is taken directly from what appears to the right of the ?. if you were to use an expression, for example: debug ? x*10/2+3 in the above code, the display would show: "x*10/2+3 = 503". a special formatter, asc, is also avai lable for use only with the ? formatter to display ascii characters, as in: debug asc ? x. what if you need to display a table of data; multiple rows and columns? the signed/unsigned code (above) approa ches this but, if you notice, the columns don't line up. the number formatters (dec, hex and bin) have some useful variations to make the di splay fixed-width (see table 5.12). up to 5 digits can be displayed for de cimal numbers. to fix the value to a specific number of decimal digits, you can use dec1, dec2, dec3, dec4 or dec5. for example: x var byte x = 165 debug dec5 x ' show decimal value of x in 5 digits d isplaying fixed - width numbers .
debug ? basic stamp command reference page 166 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com displays "00165". notice that leading zeros? the display is "fixed" to 5 digits, no more and no less. any unused digits will be filled with zeros. using dec4 in the same code would display "0165". dec3 would display "165". what would happen if we used dec2? regardless of the number, the basic stamp will ensure that it is always the exact number of digits you specified. in this case, it would truncate the "1" and only display "65". using the fixed-width version of the formatters in the signed/unsigned code above, may result in the following code: x var word x = -65 debug "signed: ", sdec5 x, " ", ishex4 x, " ", isbin16 x, cr debug "unsigned: ", dec5 x, " ", ihex4 x, " ", ibin16 x and displays: signed: -00065 -$0041 -%0000000001000001 unsigned: 65471 $ffbf %1111111110111111 note: the columns don't line up exactl y (due to the extra "sign" characters in the first row), but it certainly looks better than the alternative. if you have a string of characters to display (a byte array), you can use the str formatter to do so. the str formatter has two forms (as shown in table 5.11) for variable-width and fixed-width data. the example below is the variable-width form. x var byte(5) x(0) = "a" x(1) = "b" x(2) = "c" x(3) = "d" x(4) = 0 debug str x this code displays "abcd" on the scr een. in this form, the str formatter displays each character contained in the byte array until it finds a character that is equal to 0 (value 0, not "0"). this is convenient for use with the serin command's str formatter, which appends 0's to the end of variable-width character string in puts. note: if your byte array d isplaying strings ( byte arrays ). v ariable - width strings .
5: basic stamp command reference ? debug basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 167 doesn't end with 0, the basic stamp will read and output all ram register contents until it finds a 0 or until it cycles through all ram locations. to specify a fixed-width format for the str formatter, use the form str x\n; where x is the byte array and n is the number of characters to print. changing the debug line in the example above to: debug str x\2 would display "ab" on the screen. if you need to display the same ascii character multiple times, the rep (repeat) formatter can help. rep takes the form: rep x\n ;where x is the character and n is the number of times to repeat it. for example: debug rep "-"\10 would display 10 hyphens on the screen, "----------". since individual debug instructions can grow to be fairly complicated, and since a program can contain many debugs, you?ll probably want to control the character positioning of the debug terminal screen. debug supports a number of different contro l characters, some with pre-defined symbols (see table 5.13). all of the control characters have pre-defined symbols associated with them. in your debug commands, you can use those symbols, for example: debug "hello", cr displays "hello" followed by a carriage return. you can always use the ascii value for any of the control characters, however. for example: debug "hello", 13 is exactly the same as the code above. the move to (x,y) control character allows positioning to a specific column and row of the display. if the debug terminal receives this character, it expects to see an x and y position value to follow (in the next two characters received). the following line moves the cursor to column number 4 in row number 5 and displays "hello": ' {$pbasic 2.5} debug crsrxy, 4, 5, "hello" f ixed - width strings . r epeating characters . s pecial c ontrol characters .
debug ? basic stamp command reference page 168 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the upper-left cursor position is 0,0 (that is column 0, row 0). the right- most cursor positions depend on the size of the debug terminal window (which is user adjustable). if a character position that is out of range is received, the debug terminal wraps back around to the opposite side of the screen. the move to column (x) and move to row (y) control characters work similarly to move to (x,y) except they only expect a singe position value to follow. the clear right (clreol) control char acter clears the characters that appear to the right of, and on, the cursor's current position. the cursor is not moved by this action. the clear down (crldn) control character clears the characters that appear below, and on, the cursor's current line. the cursor is not moved by this action. name symbol ascii value description clear screen cls 0 clear the screen and place cursor at home position. home home 1 place cursor at home in upper-left corner of the screen. move to (x,y) crsrxy 2.5 2 move cursor to specified location. must be followed by two values (x and then y) cursor left crsrlf 2.5 3 move cursor one character to left. cursor right crsrrt 2.5 4 move cursor one character to right. cursor up crsrup 2.5 5 move cursor one character up. cursor down crsrdn 2.5 6 move cursor one character down. bell bell 7 beep the pc speaker. backspace bksp 8 back up cursor to left one space. tab tab 9 tab to the next column. line feed lf 2.5 10 move cursor down one line. clear right clreol 2.5 11 clear line contents to the right of cursor. clear down clrdn 2.5 12 clear screen contents below cursor. carriage return cr 13 move cursor to the first column of the next line (shift any data on the right down to that line as well). move to column x crsrx 2.5 14 move cursor to specified column. must be followed by byte value (x) for the column (0 is the left-most column). move to row y crsry 2.5 15 move cursor to specified row. must be followed by byte value (y) for the row (0 is the top-most row). table 5.13: special debug control characters for all bs2 models. note: ( 2.5 ) indicates this control character requires the pbasic 2.5 compiler directive.
5: basic stamp command reference ? debug basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 169 on all the bs2 models, debug is actually a special case of the serout instruction. it is set for inverted (rs-232-compatible) serial output through the programming connector (the sout pi n) at 9600 baud, no parity, 8 data bits, and 1 stop bit. for example, debug "hello" is exactly like: ' {$stamp bs2} serout 16, $4054, ["hello"] in terms of function on a bs2. the debug line actually takes less program space, and is obviously easier to type. another method to decrease program space is to reduce the number of debug instructions by spreading debug data across multiple lines. to do this, each line that wraps around must end with a comma as in the example below: ' {$pbasic 2.5} debug "this is line 1", cr, "this is line 2" the example above works identically to , but uses less program space than this version: debug "this is line 1", cr debug "this is line 2" note that spreading a debug statement across multiple lines requires the declaration of pbasic 2.5 syntax. you may view debug's output using a terminal program set to the above parameters, but you may have to modify either your development board or the serial cable to temporarily disc onnect pin 3 of the basic stamp (pin 4 of the db-9 connector). see the serout command for more detail. a demo program for all bs2 models that uses debug and debugin commands can be found at the end of the debugin section, next. t echnical b ackground all 2
debug ? basic stamp command reference page 170 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? debugin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 171 debugin bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px debugin inputdata { , inputdata } function accept information from the user via the debug terminal within the basic stamp editor program.  inputdata is list of variables and formatters that tells debugin what to do with incoming data. debugin can store data in a variable or array, interpret numeric text (decimal, binary, or hex) and store the corresponding value in a variable , wait for a fixed or variable sequence of bytes, or ignore a specified number of bytes. these actions can be combined in any order in the inputdata list. quick facts table 5.14: debugin quick facts. bs2, bs2e, bs2sx, bs2p, bs2pe bs2px serial protocol asynchronous 9600 baud n, 8, 1 inverted polarity, raw data asynchronous 19200 baud n, 8, 1 inverted polarity, raw data related commands serin and debug explanation debugin provides a convenient way for your basic stamp to accept input from the user via the debug terminal. debugin can wait for, filter and convert incoming data in powerf ul ways, using the same techniques and modifiers as serin. debugin is actually a special case of the serin instruction. it is set for inverted (rs-232-compatible) seri al input through the programming connector (the sin pin) at 9600 baud (19200 baud on bs2px), no parity, 8 data bits, and 1 stop bit. for example: debugin dec1 mynum all 2 note: debugin requires the $pbasic 2.5 compiler directive.
debugin ? basic stamp command reference page 172 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com is exactly like: ' {$stamp bs2} serin 16, $4054, [dec1 mynum] in terms of function on a bs2. th e debugin line actually takes less program space, and is obviously easier to type. example: ' {$pbasic 2.5} mynum var nib debug cls, "enter a number (1 - 5)? --> " debugin dec1 mynum if ((mynum >= 1) and (mynum <= 5)) then debug cls, "you entered: ", dec1 mynum else debug cls, "sorry, number out of range" endif end the tables below list all the special formatters and conversion formatters available to the debugin command. see the serin instruction for additional information and examples of their use. special formatter action str bytearray \l {\e} input a character string of length l into an array. if specified, an end character e causes the string input to end before reaching length l. remaining bytes are filled with 0s (zeros). wait ( value) wait for a sequence of bytes specified by value. value can be numbers separated by commas or quoted text (ex: 65, 66, 67 or ?abc?). the wait formatter is limited to a maximum of six characters. waitstr bytearray {\l} wait for a sequence of bytes matching a string stored in an array variable, optionally limited to l characters. if the optional l argument is left off, the end of the array-string must be marked by a byte containing a zero (0). skip length ignore length bytes of characters. table 5.15: debugin special formatters. there is an additional special formatter for the bs2p, bs2pe, and bs2px: special formatter action spstr l input a character string of length l bytes (up to 126) into scratch pad ram, starting at location 0. use get to retrieve the characters. table 5.16: debugin additional special formatter for the bs2p, bs2pe, and bs2px.
5: basic stamp command reference ? debugin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 173 table 5.17: debugin conversion formatters. conversion formatter type of number numeric characters accepted notes dec{1..5} decimal, optionally limited to 1 ? 5 digits 0 through 9 1 sdec{1..5} signed decimal, optionally limited to 1 ? 5 digits -, 0 through 9 1,2 hex{1..4} hexadecimal, optionally lim ited to 1 ? 4 digits 0 through 9, a through f 1,3,5 shex{1..4} signed hexadecimal, optionally limited to 1 ? 4 digits -, 0 through 9, a through f 1,2,3 ihex{1..4} indicated hexadecimal, optionally limited to 1 ? 4 digits $, 0 through 9, a through f 1,3,4 ishex{1..4} signed, indicated hexadecimal, optionally limited to 1 ? 4 digits -, $, 0 through 9, a through f 1,2,3,4 bin{1..16} binary, optionally limited to 1 ? 16 digits 0, 1 1 sbin{1..16} signed binary, optionally limited to 1 ? 16 digits -, 0, 1 1,2 ibin{1..16} indicated binary, optionally limited to 1 ? 16 digits %, 0, 1 1,4 isbin{1..16} signed, indicated binary, optionally limited to 1 ? 16 digits -, %, 0, 1 1,2,4 num generic numeric input (decimal, hexadecimal or binary); hexadecimal or binary number must be indicated $, %, 0 through 9, a through f 1, 3, 4 snum similar to num with value treated as signed with range -32768 to +32767 -, $, %, 0 through 9, a through f 1,2,3,4 1 all numeric conversions will continue to accept new data until receiving either the specified number of digits (ex: three digits fo r dec3) or a non-numeric character. 2 to be recognized as part of a number, the minus sign (-) must i mmediately precede a numeric character. the minus sign character occurring in non-numeric text is ignored and any character (including a space) between a minus and a number causes the minus to be ignored. 3 the hexadecimal formatters are not case-sensitive; ?a? through ?f? means the same as ?a? through ?f?. 4 indicated hexadecimal and binary formatters ignore all characters, even valid numerics, until they receive the appropriate prefix ($ fo r hexadecimal, % for bi nary). the indicated formatters can differentiate between text and hexadecimal (ex: abc would be interpreted by hex as a number but ihex would ignore it unless expressed as $abc). likewise, the binary version can dist inguish the decimal number 10 fr om the binary number %10. a prefix occurring in non-numeric text is i gnored, and any character (including a space) between a prefix and a number causes the prefix to be ignored. indicated, signed formatters require that the minus sign co me before the prefix, as in -$1b45. 5 the hex modifier can be used for decimal to bcd conversion. see ?hex to bcd conversion? on page 97. for examples of all conversion formatters and how they process incoming data, see appendix c.
debugin ? basic stamp command reference page 174 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com demo program (debugin.bs2) ' debugin.bs2 ' this program demonstrates the ability to accept user input from the ' debug terminal, and to accept numeric entry in any valid format. ' {$stamp bs2} ' {$pbasic 2.5} mynum var word main: do debug cls, "enter any number: " ' prompt user debugin snum mynum ' retrieve number in any format debug cls, ' display number in all formats sdec ? mynum, shex ? mynum, sbin ? mynum pause 3000 loop ' do it again end all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? do...loop basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 175 do?loop bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px do { while | until condition(s) } statement(s) loop { while | until condition(s) } function create a repeating loop that executes the statement(s) , one or more program lines that form a code bloc k, between do and loop, optionally testing condition(s) before or after the statement(s) .  condition is an optional variable/constant/expression (0 - 65535) which determines whether the loop will run or terminate. condition must follow while or until.  statement is any valid pbasic instruction. quick facts table 5.18: do...loop quick facts. all bs2 models maximum nested loops 16 while condition evaluation run loop if condition evaluates as true until condition evaluation terminate loop if condition evaluates as true related commands for...next and exit explanation do...loop loops let a program execute a series of instructions indefinitely or until a specified condition terminat es the loop. the simplest form is shown here: ' {$pbasic 2.5} do debug "error...", cr pause 2000 loop in this example the error message will be printed on the debug screen every two seconds until the basic st amp is reset. simple do...loop loops can be terminated with exit. all 2 note: do...loop requires the pbasic 2.5 compiler directive.
do...loop ? basic stamp command reference page 176 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com for example: ' {$pbasic 2.5} ackpin pin 0 pressed con 1 do debug "error...", cr if (ackpin = pressed) then exit ' wait for user button press pause 2000 loop goto initialize ' re-initialize system in this case the do...loop will continue until the pin called ackpin is equal to pressed (1), and then the loop will terminate and continue at the line goto initialize. more often than not, you will want to test some condition to determine whether the code block should run or co ntinue to run. a loop that tests the condition before running code block is constructed like this: ' {$pbasic 2.5} reps var nib do while (reps < 3) ' test before loop statements debug "*" reps = reps + 1 loop in this program the instructions debug "*" and reps = reps + 1 will not run unless the while condition evaluates as true. another way to write the loop is like this: ' {$pbasic 2.5} reps var nib do debug "*" reps = reps + 1 loop until (reps >= 3) ' test after loop statements the difference is that with this loop, the code block will always be run at least once before the condition is tested and will continue to run as long as the until condition ev aluates as false.
5: basic stamp command reference ? do...loop basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 177 note that the while test (loop runs while condition is true) and until test (loop runs until condition is true) can be interchanged, but they are generally used as illustrated above. demo program (do-loop.bs2) ' do-loop.bs2 ' this program creates a little guessing game. it starts by creating ' a (pseudo) random number between 1 and 10. the inner loop will run ' until the answer is guessed or 10 tries have been attempted. the ' outer loop has no condition and will cause the inner loop code to ' run until the basic stamp is reprogrammed. ' {$stamp bs2} ' {$pbasic 2.5} rval var word ' random value answer var byte ' game answer guess var byte ' player guess tries var nib ' number of tries main: do random rval answer = rval.lowbyte */ 10 + 1 ' create 1 - 10 answer tries = 0 do ' get answer until out of tries debug cls, "guess a number (1 - 10): " debugin dec guess ' get new guess tries = tries + 1 ' update tries count loop until ((tries = 10) or (guess = answer)) if (guess = answer) then ' test reason for loop end debug cr, "you got it!" else debug cr, "sorry ... the answer was ", dec answer, "." endif pause 1000 loop ' run again end note: this example program can be used with all bs2 models by changing the $stamp directive accordingly. all 2
do...loop ? basic stamp command reference page 178 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? dtmfout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 179 dtmfout bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px dtmfout pin, { ontime, offtime, } [ tone { , tone? } ] function generate dual-tone, multifrequency tones (dtmf, i.e., telephone ?touch? tones).  pin is a variable/constant/expression (0 ? 15) that specifies the i/o pin to use. this pin will be set to output mode during generation of tones and set to input mode afterwards.  ontime is an optional variable/constant/expression (0 ? 65535) specifying a duration of the tone. the unit of time and the default time for ontime is described in table 5.19.  offtime is an optional variable/constant/expression (0 ? 65535) specifying the length of silent paus e after a tone (or between tones, if multiple tones are specified). the unit of time and the default time for offtime is described in table 5.19.  tone is a variable/constant/expression (0 ? 15) specifying the dtmf tone to generate. tones 0 through 11 correspond to the standard layout of the telephone keypad, while 12 through 15 are the fourth- column tones used by phone test equipment and in ham-radio applications. quick facts table 5.19: dmtfout quick facts. bs2, bs2e bs2sx bs2p bs2pe bs2px default ontime 200 ms 80 ms 55 ms 196 ms 34 ms default offtime 50 ms 50 ms 50 ms 50 ms 50 ms units in ontime 1 ms 0.4 ms 0.265 ms 1 ms 0.166 ms units in offtime 1 ms 1 ms 1 ms 1 ms 1 ms related command freqout explanation dtmf tones are used to dial the phone or remotely control certain radio equipment. the basic stamp can gene rate these tones digitally using the dtmfout instruction. figure 5.4 sh ows how to connect a speaker or audio amplifier to hear these tones and figure 5.5 shows how to connect the basic stamp to the phone line. all 2
dtmfout ? basic stamp command reference page 180 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the following dtmfout instruction will generate dtmf tones on i/o pin 10: dtmfout 10, [6, 2, 4, 8, 3, 3, 3] ' call parallax if the basic stamp is connected to the phone line properly, the above command would be equivalent to dialing 624-8333 from a phone keypad. if you wanted to slow the pace of the dialing to accommodate a noisy phone line or radio link, you could use the optional ontime and offtime values: dtmfout 10, 500, 100, [ 6, 2, 4, 8, 3, 3, 3] ' call parallax, slowly in this example, on a bs2 the ontime is set to 500 ms (1/2 second) and offtime to 100 ms (1/10th second). tone value corresponding telephone key 0 ? 9 digits 0 through 9 10 star (*) 11 pound (#) 12 ? 15 fourth column tones a through d table 5.20: dtmf tones and corresponding telephone keys. from i/o pin 1k 0.1 f0.01 f 1k driving an audio amplifier amplifier (e .g., radio shack 277-1008c) vss vss vss 10 f (both) + + 40 ? speaker (or 8 ? in series with 33 ? resistor) from i/o pin c1 c2 notes: c1 may be omitted for piezo speakers c2 is optional, but reduces high-frequency noise driving a speaker vss vss figure 5.4: example rc filter circuits for driving an audio amplifier (top) or a speaker (bottom).
5: basic stamp command reference ? dtmfout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 181 the basic stamp microcontroller is a purely digital device. dtmf tones are analog waveforms, consisting of a mixture of two sine waves at different audio frequencies. so how does a digital device generate analog output? the basic stamp creates and mixes the sine waves mathematically, then uses the resultin g stream of numbers to control the duty cycle of a very fast pulse-width modulation (pwm) routine. so what?s actually coming out of the i/o pin is a rapid stream of pulses. the purpose of the filtering arrangements sh own in figure 5.4 and figure 5.5 is to smooth out the high-frequency pwm, leaving only the lower frequency audio behind. keep this in mind if you want to in terface basic stamp's dtmf output to radios and other equipment that could be adversely affected by the presence of high-frequency noise on the input. make sure to filter the dtmf output thoroughly. the circuits in figure 5.4 are only a starting point; you may want to use an active low-pass filter with a roll-off point around 2 khz. figure 5.5: example daa circuit to interface to a standard telephone line. jameco (jc), 1-800-831-4242 or 415-592-8097 interfacing to the telephone line 600-600 ? transformer (jc: 117760) 270v ?sidactor? (dk: p3000aa61-nd p3000aa61-nd) 10 ? (both) 3.9v zeners (both) dk: 1n5228bct-nd phone line (red and green) 0.001 f 0.1 f 1 k ? connect switch (or relay contacts) digi-key (dk), 1-800-344-4539 or 218-681-6674 from i/o pin vss demo program (dtmfout.bs2) ' dtmfout.bs2 ' this demo program is a rudimentary memory dialer. since dtmf digits fit ' within a nibble (four bits), the program below packs two dtmf digits into ' each byte of three eeprom data tables. the end of phone number is marked ' by the nibble $f, since this is not a valid phone-dialing digit. ' conditional compilation sets the timing adjustment factor so that the ' output will sound the same on any bs2 model. t echnical b ackground . note: this example program can be used with all bs2 models. this program uses conditional compilation techniques; see chapter 3 for more information. all 2
dtmfout ? basic stamp command reference page 182 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com ' {$stamp bs2} ' {$pbasic 2.5} spkr pin 10 ' dtmf output on pin 10 #select $stamp #case bs2, bs2e, bs2pe tmadj con $100 ' x 1.0 (time adjust) #case bs2sx tmadj con $280 ' x 2.5 #case bs2p tmadj con $3c5 ' x 3.77 #case bs2px tmadj con $607 ' x 6.03 #endselect eeloc var byte ' eeprom address of stored number eebyte var byte ' byte containing two dtmf digits dtdig var eebyte.nib1 ' digit to dial phone var nib ' pick a phone # hilo var bit ' bit to select upper and lower nib parallax data $19,$16,$62,$48,$33,$3f ' phone: 1-916-624-8333 parallaxfax data $19,$16,$62,$48,$00,$3f ' phone: 1-916-624-8003 information data $15,$20,$55,$51,$21,$2f ' phone: 1-520-555-1212 main: for phone = 0 to 2 ' retrieve address lookup phone, [parallax, parallaxfax, information], eeloc gosub dial_number pause 2000 next end dial_number: do read eeloc, eebyte ' retrieve byte from eeprom eeloc = eeloc + 1 ' point to next pair of digits for hilo = 0 to 1 ' dial upper and lower digits if (dtdig = $f) then exit ' hex $f is end-of-number flag dtmfout spkr, ' dial digit 150 */ tmadj, 25, [dtdig] ' 150 ms on, 25 ms off eebyte = eebyte << 4 ' shift in next digit next loop until (dtdig = $f) return
5: basic stamp command reference ? eeprom basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 183 eeprom bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px eeprom { location , } ( dataitem {, dataitem ?} ) (see data) function write data to the eeprom during program download.  location is an optional variable/constant (0 ? 255) that specifies the starting location in the eeprom at which data should be stored. if no location is given, data is wri tten starting at the next available location.  dataitem is a constant (0 ? 255) to be stored in eeprom. quick facts table 5.21: eeprom quick facts. bs1 special notes writes values to eeprom during download. can be used to decrease program size. related commands read and write explanation when you download a program into the basic stamp 1, it is stored in the eeprom starting at the highest address (255) and working towards the lowest address. most programs don?t use the entire eeprom, so the lower portion is available for other uses. the eeprom directive allows you to define a set of data to store in the available eeprom locations. it is called a ?directive? rather than a ?command? because it performs an activity at compile-time rather than at run-time (i.e.: the eeprom directive is not downloaded to the basic stamp 1, but the data it contains is downloaded). the simplest form of the eeprom directive is something like the following: eeprom (100, 200, 52, 45) this example, when downloaded, will cause the values 100, 200, 52 and 45 to be written to eeprom locations 0, 1, 2 and 3, respectively. you can then use the read and write commands in your code to access these locations and the data you?ve stored there. w riting simple , sequential data . 1 all 2
eeprom ? basic stamp command reference page 184 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the eeprom directive uses a counter, called a pointer, to keep track of available eeprom addresses. the value of the pointer is initially 0. when a program is downloaded, the eeprom directive stores the first byte value at the current pointer address, then increments (adds 1 to) the pointer. if the program contains more than one eeprom directive, subsequent eeprom directives start wi th the pointer value left by the previous eeprom directive. for example, if the program contains: eeprom (72, 69, 76, 76, 79) eeprom (104, 101, 108, 108, 111) the first eeprom directive will start at location 0 and increment the pointer for each data value it stores (1, 2, 3, 4 and 5). the second eeprom directive will start with the pointer value of 5 and work upward from there. as a result, the first 10 bytes of eeprom will look like the following: eeprom location (address) 0 1 2 3 4 5 6 7 8 9 contents 72 69 76 76 79 104 101 108 108 111 table 5.22: example eeprom storage. what if you don?t want to store values starting at location 0? fortunately, the eeprom directive has an option to specify the next location to use. you can specify the next location numb er (to set the pointer to) by using the optional location argument before the list of dataitems . the following code writes the same data in table 5.22 to locations 50 through 59: eeprom 50, (72, 69, 76, 76, 79, 104, 101, 108, 108, 111) in this example, the location argument is given and tells the eeprom directive to store the following dataitem(s) starting at location 50. the dataitems in the list are stored in their respective locations (50, 51, 52? 59). it is important to realize that the entire basic stamp 1 eeprom is overwritten during programming. an y eeprom location not containing a pbasic program or dataitems from an eeprom directive is written with a 0. a common use for eeprom is to store strings; sequences of bytes representing text. pbasic converts quoted text like "a" into the corresponding ascii character code (65 in this case). to make data entry easier, you can place quotes around a whole chunk of text used in an t he eeprom pointer ( counter ). w riting data to other locations . w riting text strings . i mportant concept : h ow data and programs are downloaded into eeprom.
5: basic stamp command reference ? eeprom basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 185 eeprom directive, and pbasic will unde rstand it to mean a series of bytes (see the last line of code below). the following three eeprom directives are equivalent: eeprom (72, 69, 76, 76, 79) eeprom ("h", "e", "l", "l", "o") eeprom ("hello") all three lines of code, above, will result in the numbers 72, 69, 76, 76, and 79 being stored into eeprom upon downloading. these numbers are simply the ascii character codes for "h", "e", "l", "l", and "o", respectively. see the demo program, below, for an example of storing and reading multiple text strings. the eeprom is organized as a sequential set of byte-sized memory locations. the eeprom directive only stores bytes into eeprom. if you try to store a word-sized value, for example: eeprom (1125), only the lower byte of the value will be stored (in this case, 101). this does not mean that you can't store word-sized values, however. a word consists of two bytes, called a low-byte and a high -byte. if you wanted to store the value 1125 using the eeprom directive you'll have to calculate the low- byte and the high-byte and insert them in the list in the proper order, as in: eeprom (101, 4) the directive above will store the tw o bytes into two sequential eeprom locations (the low-byte first, follow ed by the high-byte). we calculated this in the following manner: 1) high-byte is int(value / 256) and 2) low- byte is value ? (high-byte * 256). to retrieve a word-sized value, you'll need to use two read commands and a word-sized variable. for example, symbol result = w0 ' word-sized variable symbol resultlo = b0 ' b0 is the low-byte of w0 symbol resulthi = b1 ' b1 is the high-byte of w0 eeprom (101, 4) read 0, resultlo read 1, resulthi debug #result this code would write the low-byte and high-byte of the number 1125 into locations 0 and 1 during download. when the program runs, the two w riting word values vs . byte values .
eeprom ? basic stamp command reference page 186 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com read commands will read the low- byte and high-byte out of eeprom (reconstructing it in a word-sized va riable) and then display the value on the screen. see the read and write commands for more information. demo program (eeprom.bs1) ' eeprom.bs1 ' this program stores a couple of text strings into eeprom with the eeprom ' directive and then sends them, one character at a time via the serout ' command. this is a good demonstration of how to save program space by ' storing large amounts of data in eeprom directly, rather than embedding ' the data into serout commands. ' {$stamp bs1} ' {$pbasic 1.0} symbol sout = 0 ' serial output symbol idx = b2 ' holds current location number symbol phrase = b3 symbol char = b4 ' holds current character to print phrases: eeprom ("here is a long message that needs to be transmitted.", 13, 0) eeprom ("here is some more text to be transmitted.", 13, 0) main: idx = 0 for phrase = 1 to 2 ' select phrase gosub print_it ' print the phrase pause 3000 ' pause for 3 seconds next end print_it: read idx, char ' get next character idx = idx + 1 ' point to next eeprom location if char = 0 then print_done ' if 0, we're done with this block serout sout, n2400, (char) ' otherwise, transmit it 'debug #@char ' -- for demo with debug (slower) goto print_it print_done: return ' return to caller 1
5: basic stamp command reference ? end basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 187 end bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px end function end the program, placing the basic stamp into low-power mode indefinitely. this is equivalent to having a program that does not loop continuously; once the basic stamp reaches the end of the pbasic program, it enters low-power mode indefinitely. the end command is optional. quick facts table 5.23: end quick facts. note: current measurements are based on 5-volt power, no extra loads, and 75 f ambient temperature. bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px current draw during run 1 ma 3 ma 25 ma 60 ma 40 ma 15 ma 55 ma current draw during sleep 25 a 50 a 200 a 500 a 350 a 36 a 450 a related commands nap and sleep nap, sleep and stop nap, sleep, stop and pollwait explanation end puts the basic stamp into its inactive, low-power mode. in this mode the stamp's current draw (excluding loads driven by the i/o pins) is reduced to the amount shown in table 5.23. end keeps the basic stamp inactive until the reset line is activated, the power is cycled off and back on or the pc downloads another program. just as with the sleep command, pins will retain their input or output settings after the basic stamp is deacti vated by end. for example, if the basic stamp is powering an led when end executes, the led will stay lit after end, but every 2.3 seconds, there will be a visible wink of the led as the output pin switches to the input direction for 18 ms (60 s on the bs2pe). (see the sleep command for more information). 1 a ll 2
end ? basic stamp command reference page 188 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? exit basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 189 exit bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px exit function causes the immediate termination of a loop construct (do...loop, for...next). quick facts table 5.24: exit quick facts. all bs2 models maximum exits per loop 16 related commands do...loop and for...next explanation the exit instruction allows a prog ram to terminate a loop structure before the loop limit test is executed . while not required, exit is usually used as part of an if...then construct to test a secondary condition for terminating a loop, or for testin g a termination condition of an unconditional do...loop structure. for example, the following subroutine will send characters from a data statement to a serial port until a 0 byte is encountered in the data: ' {$pbasic 2.5} do read eeaddr, char ' get character from data statement eeaddr = eeaddr + 1 ' update address pointer if (char = 0) then exit ' if 0, end of string debug char ' otherwise, transmit the character loop ' get next character return demo program (exit.bs2) ' exit.bs2 ' this program demonstrates the early termination of do...loop and ' for..next loop structures. if...then is used to test a condition ' and when true, exit will terminate the loop. ' {$stamp bs2} ' {$pbasic 2.5} col var nib all 2 note: exit requires the pbasic 2.5 compiler directive. note: this example program can be used with all bs2 models by changing the $stamp directive accordingly. all 2
exit ? basic stamp command reference page 190 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com row var nib setup: col = 0 main: do while (col < 10) ' attempt 10 iterations for row = 0 to 15 ' attempt 16 iterations if (row > 9) then exit ' terminate when row > 9 debug crsrxy, (col * 8), row, ' print col/row at location dec col, "/", dec row, cr next col = col + 1 ' update column if (col = 3) then exit ' terminate when col = 3 loop end
5: basic stamp command reference ? for...next basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 191 for?next bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px for counter = startvalue to endvalue { step {-} stepvalue } statement(s) next { counter } for counter = startvalue to endvalue { step stepvalue } statement(s) next { counter } function create a repeating loop that executes the statement(s) , one or more program lines that form a code block, between for and next, incrementing or decrementing counter according to stepvalue until the value of the counter variable passes the endvalue .  counter is a variable (usually a byte or a word) used as a counter.  startvalue is a variable/constant/expression (0 ? 65535) that specifies the initial value of the variable ( counter ).  endvalue is a variable/constant/expression (0 ? 65535) that specifies the end value of the variable ( counter ). when the value of counter is outside of the range startvalue to endvalue , the for...next loop stops executing and the program goes on to the instruction after next.  stepvalue is an optional variable/constant/expression (0 ? 65535) by which the counter increases or decreases with each iteration through the for?next loop. on the bs1, use a minus sign (-) in front of the stepvalue to indicate a negative step. on all bs2 models, if startvalue is larger than endvalue , pbasic understands stepvalue to be negative, even though no minus sign is used.  statement is any valid pbasic instruction. note: expressions are not allowed as arguments on the bs1. note: use a minus sign to indicate negative stepvalues on the bs1. 1 1 1 all 2
for?next ? basic stamp command reference page 192 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com quick facts bs1 all bs2 models max. nested loops 8 16 to decrement counter variable set startvalue > endvalue and enter negative stepvalue * set startvalue > endvalue counter comparison exit loop if counter exceeds endvalue exit loop if counter outside range set by startvalue to endvalue related commands none do...loop and exit table 5.25: for...next quick facts. *note: for the bs1, direction (increment or decrement) cannot be changed at run-time. explanation for...next loops let your program exec ute a series of instructions for a specified number of repetitions (called iterations). by default, each time through the loop, the counter variable is incremented by 1. it will continue to loop until the value of counter is outside of the range set by startvalue and endvalue . also, for?next loops always execute at least once. the simplest form is shown here: reps var nib ' counter for the for/next loop for reps = 1 to 3 ' repeat with reps = 1, 2, 3 debug "*" ' put * on screen for each repetition next in the above code, the for command sets reps = 1. then the debug line (within the for?next loop) is executed ; printing an asterisk (*) on the screen. when the basic stamp sees the next command, it goes back to the previous for command, adds 1 to reps and compares the result to the range set by startvalue and endvalue. if reps is still within range, it executes the code in the loop again. each time the for...next loop executes, the value of reps is updated (incremented by 1) and the code within the loop (the debug line) is executed; printing another asterisk on the screen. this code will run th rough the loop three times; setting reps to 1, 2 and 3, and printing three asterisks on the screen. after the third loop, again the basic stamp goes back up to the for command, adds 1 to reps and compares the result (4 in this case) to the range. since the range is 1 to 3 and the value is 4 (outside the rang e) the for?next loop is done and the basic stamp will jump down to the first line of code following the next command. you can view the changing values of reps by including the reps variable in a debug command within the loop: note: replace the first line with symbol reps = b0 on the bs1. s implest form of for...next. p rocessing a for?next loop . note: on the bs1, the loop will continue until counter has gone p ast endvalu e . 1 1
5: basic stamp command reference ? for...next basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 193 reps var nib ' counter for the for/next loop for reps = 1 to 3 ' repeat with reps = 1, 2, 3 debug dec reps, cr ' print rep number next running this example should display "1" , "2", and "3" on the screen. for?next can also be made to decrement (rather than increment) the counter variable. the bs1 does this when you specify a negative stepvalue (as well as a startvalue that is greater than the endvalue ). all other basic stamp models do this automatically when the startvalue is greater than the endvalue . examples of both are shown below: symbol reps = b0 ' counter for the for/next loop for reps = 3 to 1 step -1 ' repeat with reps = 3, 2, 1 debug #reps, cr ' print reps number next -- or -- reps var nib ' counter for the for/next loop for reps = 3 to 1 ' repeat with reps = 3, 2, 1 debug dec reps, cr ' print reps number next note that the code for all the bs2 models did not use the optional step argument. this is because we wanted to decrement by positive 1 anyway (the default unit) and the basic stamp realizes it needs to decrement because the startvalue is greater than the endvalue . a negative stepvalue on any bs2 model would be treated as its positive, twos complement counterpart. for example, ?1 in twos complement is 65535. so the following code executes only once: reps var nib ' counter for the for/next loop for reps = 3 to 1 step -1 ' try to decrement 3 by 65535 debug dec reps, cr ' print reps number next the above code would run through the loop once with reps set to 3. the second time around, it would decrement reps by 65535 (-1 is 65535 in twos complement) effectively making the number ?65532 (4 in twos complement) which is outside the range of the loop. d ecrementing the counter instead of incrementing it . 1 all 2 all 2 all 2 note: change the first line as noted above and replace line 3 with debug #reps, cr 1
for?next ? basic stamp command reference page 194 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com all the arguments in the for?next command can be constants, variables or expressions on all bs2 models. this leads to some interesting uses. for example, if you make the startvalue and endvalue a variable, and change their values within the loop, you'll change the behavior of the loop itself. try the following: {' $pbasic 2.5} reps var byte ' counter for the for/next loop startval var byte endval var byte startval = 1 ' initialize startval to 1 endval = 3 ' initialize endval to 3 for reps = startval to endval ' repeat for 1 to 3 debug dec reps, cr if (reps = 3) then ' if reps =3, swap startval/endval startval = 3 ' otherwise continue loop endval = 1 endif next here the loop starts with a range of 1 to 3. first, the debug line prints the value of reps . then the if?then line makes a decision; if reps is equal to 3, then swap the order of startval and endval, otherwise continue the loop execution. the next time through the loop (after startval and endval have been swapped), reps will be decremented instead of incremented because startval is greater than endval . the result is a display on the screen of the numbers 1, 2, 3, 2, 1. the following example uses the value of reps as the stepvalue . this creates a display of power's of 2 (1, 2, 4, 8, 16, 32, 64, etc): reps var word ' counter for the loop for reps = 1 to 256 step reps ' each loop add current value of reps debug dec ? reps ' show reps in debug window next there is a potential bug that you should be careful to avoid. the basic stamp uses unsigned 16-bit integer math for any math operation it performs, regardless of the size of values or variables. the maximum value the basic stamp can internally calculate is 65535 (the largest 16-bit w atch out for 16- bit rollover , or variable range , errors . u sing variables as arguments . note: for bs1's, change line 1 to symbol reps = w0 and line 3 to debug reps note: the increment/decrement direction of the for?next loop cannot be changed on the bs1. 1 1 all 2
5: basic stamp command reference ? for...next basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 195 number). if you add 1 to 65535, you ge t 0 as the 16-bit register rolls over (like a car?s odometer does when yo u exceed the maximum mileage it can display). similarly, if you subtract 1 from 0, you'll get 65535 as the 16-bit register rolls under (a rollover in the opposite direction). if you write a for...next loop who's stepvalue would cause counter to go past 65535, this rollover may cause th e loop to execute more times than you expect. try the following example: reps var word ' counter for the loop for reps = 0 to 65535 step 3000 ' each loop add 3000 debug dec ? reps ' show reps in debug window next the value of reps increases by 3000 each trip through the loop. as it approaches the endvalue , an interesting thing happens; reps is: 57000, 60000, 63000, 464, 3464... it passes the endvalue, rolls over and keeps going. that?s because the result of the calculation 63000 + 3000 exceeds the maximum capacity of a 16-bit number and then rolls over to 464. when the result of 464 is tested against the range (?is reps > 0 and is reps < 65535??) it passes the test and the loop continues. a similar symptom can be seen in a program who's endvalue is mistakenly set higher than what the counter variable can hold. the example below uses a byte-sized variable, but the endvalue is set to a number greater than what will fit in a byte: symbol reps = b2 ' counter for the loop for reps = 0 to 300 ' each loop add 1 debug reps ' show reps in debug window next -- or -- reps var byte ' counter for the loop for reps = 0 to 300 ' each loop add 1 debug dec ? reps ' show reps in debug window next here, reps is a byte variable; which can only hold the number range 0 to 255. the endvalue is set to 300, however; greate r than 255. this code will loop endlessly because when reps is 255 and the for?next loop adds 1, note: for bs1's, change line 1 to symbol reps = w0 and line 3 to debug reps 1 1 all 2
for?next ? basic stamp command reference page 196 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com reps becomes 0 (bytes will rollover afte r 255 just like words will rollover after 65535). the result, 0, is compared against the range (0 ? 255) and it is found to be within the range, so the for?next loop continues. it's important to realize that on all the bs2 models, the test is against the entire range, not just the endvalue . the code below is a slight modification of the previous example (the startvalue is 10 instead of 0) and will not loop endlessly. reps var byte ' counter for the loop for reps = 10 to 300 ' each loop add 1 debug dec ? reps ' show reps in debug window next reps still rolls over to 0, as before, however, this time it is outside the range of 10 to 255. the loop stops, leaving reps at 0. note that this code is still in error since reps will never reach 300 until it is declared as a word. demo program (for-next.bs1) ' for-next.bs1 ' this example uses a for...next loop to churn out a series of sequential ' squares (numbers 1, 2, 3, 4... raised to the second power) by using a ' variable to set the for...next stepvalue, and incrementing stepvalue ' within the loop. sir isaac newton is generally credited with the ' discovery of this technique. ' {$stamp bs1} ' {$pbasic 1.0} symbol square = b2 ' for/next counter symbol stepsize = b3 ' step size increases by 2 each loop setup: stepsize = 1 square = 1 main: for square = 1 to 250 step stepsize ' show squares up to 250 debug square ' display on screen stepsize = stepsize + 2 ' add 2 to stepsize next ' loop until square > 250 end note: on the bs1, the loop will continue until counter has gone past endvalue . the rollover error will still occur if the bs1 cannot determine if counter went past endvalue. all 2 1
5: basic stamp command reference ? for...next basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 197 demo program (for-next.bs2) ' for-next.bs2 ' this example uses a for...next loop to churn out a series of sequential ' squares (numbers 1, 2, 3, 4... raised to the second power) by using a ' variable to set the for...next stepvalue, and incrementing stepvalue ' within the loop. sir isaac newton is generally credited with the ' discovery of this technique. ' {$stamp bs2} ' {$pbasic 2.5} square var byte ' for/next counter stepsize var byte ' step size increases by 2 each loop setup: stepsize = 1 square = 1 main: for square = 1 to 250 step stepsize ' show squares up to 250 debug dec ? square ' display on screen stepsize = stepsize + 2 ' add 2 to stepsize next ' loop until square > 250 end all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
for?next ? basic stamp command reference page 198 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? freqout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 199 freqout bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px (see sound) freqout pin, duration, freq1 { , freq2 } function generate one or two sine-wave tones for a specified duration .  pin is a variable/constant/expression (0 ? 15) that specifies the i/o pin to use. this pin will be set to output mode.  duration is a variable/constant/expression (0 - 65535) specifying the amount of time to generate the tone(s). the unit of time for duration is described in table 5.26.  freq1 is a variable/constant/expression (0 ? 32767) specifying frequency of the first tone. the unit of freq1 is described in table 5.26.  freq2 is an optional argument exactly like freq1 . when specified, two frequencies will be mixed toge ther on the specified i/o pin. quick facts table 5.26: freqout quick facts. bs2, bs2e bs2sx bs2p bs2pe bs2px units in duration 1 ms 0.4 ms 0.265 ms 1 ms 0.166 ms units in freq1 and freq2 1 hz 2.5 hz 3.77 hz 1.51 hz 6.03 hz range of frequency 0 to 32767 hz 0 to 81917 hz 0 to 123531 hz 0 to 49478 hz 0 to 197585 hz related commands dtmfout and pwm explanation freqout generates one or two si ne waves using a pulse-width modulation algorithm. the circuits shown in figure 5.6 will filter the signal in order to play the tones through a speaker or audio amplifier. here?s a simple freqout command: freqout 2, 1000, 2500 s implest form of freqout. 1 all 2
freqout ? basic stamp command reference page 200 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com on the bs2, this command generates a 2500 hz tone for 1 second (1000 ms) on i/o pin 2. see table 5.26 for timing data on other basic stamp models. to play two tones on the same i/o pin at once: freqout 2, 1000, 2500, 3000 this will generate a 2500 hz and 3000 hz tone for 1 second. the frequencies will mix together for a chord- or bell-like sound. to generate a silent pause, specify frequency value(s) of 0. from i/o pin 1k 0.1 f0.01 f 1k driving an audio amplifier amplifier (e .g., radio shack 277-1008c) vss vss vss 10 f (both) + + 40 ? speaker (or 8 ? in series with 33 ? resistor) from i/o pin c1 c2 notes: c1 may be omitted for piezo speakers c2 is optional, but reduces high-frequency noise driving a speaker vss vss figure 5.6: example rc filter circuits for driving an audio amplifier(top) or a speaker (bottom). the circuits in figure 5.6 work by filtering out the high-frequency pwm used to generate the sine waves. freqout works over a very wide range of frequencies (as shown in table 5.26) so at the upper end of its range, those pwm filters will also filter ou t most of the desired frequency. you may find it necessary to reduce values of the parallel capacitors shown in the circuit, or to devise a custom ac tive filter for your application. f requency c onsiderations . g enerating two tones at once .
5: basic stamp command reference ? freqout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 201 demo program (freqout.bs2) ' freqout.bs2 ' this program demonstrates sound-effects generation by the basic stamp. ' conditional compilation sets timing and frequency adjustment factors so ' that the output will sound the same on any bs2 model. ' {$stamp bs2} ' {$pbasic 2.5} spkr pin 10 ' output pin for freqout #select $stamp #case bs2, bs2e tmadj con $100 ' x 1.0 (time adjust) fradj con $100 ' x 1.0 (freq adjust) #case bs2sx tmadj con $280 ' x 2.5 fradj con $066 ' x 0.4 #case bs2p tmadj con $3c5 ' x 3.77 fradj con $044 ' x 0.265 #case bs2pe tmadj con $100 ' x 1.0 fradj con $0a9 ' x 0.662 #case bs2px tmadj con $607 ' x 6.03 fradj con $2a ' x 0.166 #endselect main: debug "let's make a call...", cr ' combine 350 hz & 440 hz freqout spkr, 2000 */ tmadj, 350 */ fradj, 440 */ fradj ' dial number (digits 150 ms on, 25 ms off) dtmfout spkr, 150 */ tmadj, 25, [5, 5, 5, 1, 2, 1, 2] pause 500 ' bad connection (sit sequence) freqout spkr, 375 */ tmadj, 985 */ fradj freqout spkr, 375 */ tmadj, 1371 */ fradj freqout spkr, 375 */ tmadj, 1777 */ fradj debug "oops! -- try again...", cr pause 1000 dtmfout spkr, 150 */ tmadj, 25, [5, 5, 5, 2, 2, 2, 2] debug "ringing" freqout spkr, 2000 */ tmadj, 440 */ fradj, 480 */ fradj pause 4000 freqout spkr, 2000 */ tmadj, 440 */ fradj, 480 */ fradj input spkr end all 2 note: this example program can be used with all bs2 models. this program uses conditional compilation techniques; see cha p ter 3 for more information.
freqout ? basic stamp command reference page 202 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? get basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 203 get bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px get location, { word } variable { , { word } variable... } function read the value from scratch pad ram (spram) location and store in variable .  location is a variable/constant/expression (0 ? 63 for bs2e and bs2sx and 0 ? 131 for bs2p, bs2pe, and bs2px) that specifies the spram location to read from.  variable is a variable (usually a byte, or word if using the optional word modifier) in which to store the value. quick facts table 5.27: get quick facts. bs2e and bs2sx bs2p, bs2pe, and bs2px scratch pad ram size and organization 64 bytes (0 ? 63). organized as bytes only. 136 bytes (0 ? 135). organized as bytes only. general purpose locations 0 - 62 0 ? 126 special use location location 63: active program slot number (read only). location 127: read/write slot and active program slot (read only). locations 128-135: polled interrupt status (read only). related commands put put and store, and spstr formatter. pbasic 2.5 syntax options multiple sequential variables may be read from the scratch pad ram. the optional word modifier may be specified to retrieve 16-bit values. explanation the get command reads a value from the specified scratch pad ram location and stores it into variable . all values in all locations can be retrieved from within any of the 8 program slots. spram is useful for passing data to programs in other program slots and for additional workspace. it is diffe rent than regular ram in that symbol names cannot be assigned directly to lo cations and each location is always configured as a byte only. the following code will read the value at location 25, store it in a variable called temp and display it: u ses for s cratch p ad ram. note: the optional arguments require pbasic 2.5.
get ? basic stamp command reference page 204 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com temp var byte get 25, temp ' retrieve byte from location 25 debug dec temp when using the pbasic 2. 5 directive, multiple sequential variables may be read from the scratch pad ram, starting at location , and the word modifier may be specified to retrieve 16-bit values. ' {$pbasic 2.5} temp var byte temp2 var word get 25, temp, word temp2 ' retrieve byte from location 25 ' and word from locations 26 and 27 debug dec temp, cr debug dec temp2 the low nibble of location 63 (bs2e and bs2sx) and location 127 (bs2p, bs2pe, and bs2px) is a special, read-only location that always contains the number of the currently running prog ram slot. on the bs2p, bs2pe, and bs2px, the high nibble of location 127 also contains the current program slot that will be used for the read and write commands. see the demo program below for an example of use. table 5.28 shows the layout of all spram registers.
5: basic stamp command reference ? get basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 205 table 5.28: layout of spram registers. note: scratch pad ram can only be accessed with the get and put commands. scratch pad ram cannot have variable names assigned to it. location bs2e and bs2sx bs2p, bs2pe, and bs2px 0...62 general purpose ram general purpose ram 63 bits 0-3: active program slot number. general purpose ram 64..126 n/a general purpose ram 127 n/a bits 0-3, active program slot #. bits 4-7, program slot for read and write operations. 128 n/a polled input trigger status of main i/o pins 0-7 (0 = not triggered, 1 = triggered). 129 n/a polled input trigger status of main i/o pins 8-15 (0 = not triggered, 1 = triggered). 130 n/a polled input trigger status of auxiliary i/o pins 0-7 (0 = not triggered, 1 = triggered). 131 n/a polled input trigger status of auxiliary i/o pins 8-15 (0 = not triggered, 1 = triggered). 132 n/a bits 0-3: polled-interrupt mode, set by pollmode 133 n/a bits 0-2: polled-interrupt ?run? slot, set by pollrun. 134 n/a bit 0: active i/o group; 0 = main i/o, 1 = auxiliary i/o. 135 n/a bit 0: polled-output status (set by pollmode); 0 = disabled, 1= enabled. bit 1: polled-input status; 0 = none defined, 1 = at least one defined. bit 2: polled-run status (set by pollmode); 0 = disabled, 1 = enabled. bit 3: polled-output latch status; 0 = real-time mode, 1 = latch mode. bit 4: polled-input state; 0 = no trigger, 1 = triggered. bit 5: polled-output latch state; 0 = nothing latched, 1 = signal latched. bit 6: poll-wait state; 0 = no event, 1 = event occurred. (cleared by pollmode only). bit 7: polling status; 0 = not active, 1 = active. demo program (get_put1.bsx) ' get_put1.bsx ' this example demonstrates the use of the get and put commands. first, ' slot location is read using get to display the currently running program ' number. then a set of values are written (put) into locations 0 to 9. ' afterwards, program number 1 is run. this program is a bs2sx project ' consisting of get_put1.bsx and get_put2.bsx, but will run on the bs2e, ' bs2p, bs2pe and bs2px without modification. ' {$stamp bs2sx, get_put2.bsx} ' {$pbasic 2.5} note: this is written for the bs2sx but can be used with the bs2e, bs2p, bs2pe and bs2px also. this program uses conditional compilation techniques; see chapter 3 for more information.
get ? basic stamp command reference page 206 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com #select $stamp #case bs2 #error "bs2e or greater required." #case bs2e, bs2sx slot con 63 #case bs2p, bs2pe, bs2px slot con 127 #endselect value var byte idx var byte setup: get slot, value debug "program slot #", dec value.nib0, cr main: for idx = 0 to 9 value = (idx + 3) * 8 put idx, value debug " writing: ", dec2 value, " to location: ", dec2 idx, cr next debug cr run 1 end demo program (get_put2.bsx) ' get_put2.bsx ' this example demonstrates the use of the get and put commands. first, ' the slot location is read using get to display the currently running ' program number. then a set of values are read (get) from locations ' 0 to 9 and displayed on the screen for verification. this program is a ' bs2sx project consisting of get_put1.bsx and get_put2.bsx, but will run ' on the bs2e, bs2p, bs2pe, and bs2px without modification. ' {$stamp bs2sx} ' {$pbasic 2.5} #select $stamp #case bs2 #error "bs2e or greater required." #case bs2e, bs2sx slot con 63 #case bs2p, bs2pe, bs2px slot con 127 #endselect value var byte idx var byte note: this is written for the bs2sx but can be used with the bs2e, bs2p, bs2pe and bs2px also. this program uses conditional compilation techniques; see chapter 3 for more information.
5: basic stamp command reference ? get basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 207 setup: get slot, value debug "program slot #", dec value.nib0, cr main: for idx = 0 to 9 get idx, value debug " reading: ", dec2 value, " from location: ", dec2 idx, cr next end
get ? basic stamp command reference page 208 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? gosub basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 209 gosub bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px gosub address function store the address of the next instruction after gosub, then go to the point in the program specified by address ; with the intention of returning to the stored address.  address is a label that specifies where to go. quick facts table 5.29: gosub quick facts. bs1 all bs2 models max. gosubs per program 16 255 max. nested gosubs 4 4 related commands goto on...gosub and goto explanation gosub is a close relative of goto, in fact, its name means, "go to a subroutine". when a pbasic program reaches a gosub, the program executes the code beginning at the specified address label. unlike goto, gosub also stores the address of the instruction immediately following itself. when the program encounters a return command, it interprets it to mean, ?go to the instruction that fo llows the most recent gosub.? in other words, a gosub makes the basic stamp do a similar operation as you do when you see a table or figure reference in this manual; 1) you remember where you are, 2) you go to the table or figure and read the information there, and 3) when you've reached the end of it, you "return" to the place you were reading originally. gosub is mainly used to execute the same piece of code from multiple locations. if you have, for example, a block of three lines of code that need to be run from 10 different locations in your entire program you could simply copy and paste those three lines to each of those 10 locations. this would amount to a total of 30 lines of repetitive code (and extra space wasted in the program memory). a bett er solution is to place those three lines in a separate routine, complete with it's own label and followed by a gosub can save eeprom ( program ) space . 1 a ll 2
gosub ? basic stamp command reference page 210 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com return command, then just use a gosub command at each of the 10 locations to access it. this technique can save a lot of program space. try the example below: main: gosub hello debug "how are you?" end hello: debug "hello, my friend!", cr return the above code will start out by gosub'ing to the section of code beginning with the label hello . it will print "hello, my friend!" on the screen then return to the line after the gosub? which prints "how are you?" and ends. note: colons ( : ) are placed after labels, as in ? ?main: ? and ?hello:? but the colon is not used on references to these labels such as in the ?gosub hello? line. there's another interesting lesson here; what would happen if we removed the end command from this example? since the basic stamp reads the code from left to right / top to bottom (like the english language) once it had returned to and run the "how are you?" line, it would naturally "fall into" the hello routine again. additionally, at the end of the hello routine, it would see the return again (althoug h it didn't gosub to that routine this time) and because there wasn't a previous place to return to, the basic stamp will start the entire program over again. this would cause an endless loop. the important thing to remember here is to always make sure your program doesn't allow itself to "fall into" a subroutine. a limited number of gosubs are allowed per program (as shown in table 5.29), and they may be nested only four levels deep. in other words, the subroutine that?s the destination of a gosub can contain a gosub to another subroutine, and so on, to a maximum depth (total number of gosubs before the first return) of four. any deeper, and the program will "forget" its way back to the star ting point (the instruction following the very first gosub). when gosubs are nested, each retu rn takes the program back to the instruction after the most-recent gosub. as is mentioned above, if the w atch out for subroutines that your program can " fall into ." gosub limitations . note: on the bs1, a return without a gosub will return the program to the last gosub (or will end the program if no gosub was executed). 1
5: basic stamp command reference ? gosub basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 211 basic stamp encounters a return without a previous gosub, the entire program starts over from the beginning. take care to avoid these phenomena. demo program (gosub.bs1) ' gosub.bs1 ' this program is a guessing game that generates a random number in a ' subroutine called pick_a_number. it is written to stop after ten ' guesses. to see a common bug associated with gosub, delete or comment ' out the line beginning with end after the for-next loop. this means ' that after the loop is finished, the program will wander into the ' pick_a_number subroutine. when the return at the end executes, the ' program will go back to the beginning of the program. this will cause ' the program to execute endlessly. make sure that your programs can't ' accidentally execute subroutines! ' {$stamp bs1} ' {$pbasic 1.0} symbol rounds = b2 ' number of reps symbol numgen = w0 ' random number holder symbol mynum = b3 ' random number, 1-10 setup: numgen = 11500 ' initialize random "seed" main: for rounds = 1 to 10 debug cls, "pick a number from 1 to 10", cr gosub pick_a_number pause 2000 ' dramatic pause debug "my number was: ", #mynum ' show the number pause 1000 ' another pause. next debug cls, "done" end ' end program ' random-number subroutine. a subroutine is just a piece of code with ' the return instruction at the end. always make sure your program enters ' subroutines with a gosub. if you don't, the return won't have the ' correct address, and your program will have a bug! pick_a_number: random numgen ' stir up the bits of numgen. debug numgen, cr mynum = numgen / 6550 min 1 ' scale to fit 1-10 range. return ' go back to 1st instruction ' after gosub that got us here 1
gosub ? basic stamp command reference page 212 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com demo program (gosub.bs2) ' gosub.bs2 ' this program is a guessing game that generates a random number in a ' subroutine called pick_a_number. it is written to stop after ten ' guesses. to see a common bug associated with gosub, delete or comment ' out the line beginning with end after the for-next loop. this means ' that after the loop is finished, the program will wander into the ' pick_a_number subroutine. when the return at the end executes, the ' program will go back to the beginning of the program. this will cause ' the program to execute endlessly. make sure that your programs can't ' accidentally execute subroutines! ' {$stamp bs2} ' {$pbasic 2.5} rounds var byte ' number of reps numgen var word ' random number holder mynum var byte ' random number, 1-10 setup: numgen = 11500 ' initialize random "seed" main: for rounds = 1 to 10 debug cls, "pick a number from 1 to 10", cr gosub pick_a_number pause 2000 ' dramatic pause debug "my number was: ", dec mynum ' show the number pause 1000 ' another pause. next debug cls, "done" end ' end program ' random-number subroutine. a subroutine is just a piece of code with ' the return instruction at the end. always make sure your program enters ' subroutines with a gosub. if you don't, the return won't have the ' correct address, and your program will have a bug! pick_a_number: random numgen ' stir up the bits of numgen. debug dec ? numgen mynum = numgen / 6550 min 1 ' scale to fit 1-10 range. return ' go back to 1st instruction ' after gosub that got us here all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? goto basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 213 goto bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px goto address function go to the point in the program specified by address .  address is a label that specifies where to go. quick facts table 5.30: goto quick facts. bs1 all bs2 models related commands branch and gosub on...goto, branch and gosub max. gotos per program unlimited, but good programming practices suggest using the least amount possible. explanation the goto command makes the basic stamp execute the code that starts at the specified address location. the basic stamp reads pbasic code from left to right / top to bottom, ju st like in the english language. the goto command forces the basic stam p to jump to another section of code. a common use for goto is to create endless loops; programs that repeat a group of instructions over and over. for example: start: debug "hi", cr goto start the above code will print "hi" on the screen, over and over again. the goto start line simply tells it to go back to the code that begins with the label start . note: colons ( : ) are placed after labels, as in ?start:? to further indicate that they are labels, but the colon is not used on references to labels such as in the ?goto start? line. demo program (goto.bs2) ' goto.bs2 ' this program is not very practical, but demonstrates the use of goto to ' jump around the code. this code jumps between three different routines, ' each of which print something different on the screen. the routines are ' out of order for this example. 1 a ll 2 1 a ll 2 note: this is written for the bs2 but can be used for the bs1 and all other bs2 models as well, by modifying the $stamp directive accordingly.
goto ? basic stamp command reference page 214 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com '{$stamp bs2} goto routine1 routine2: debug "we're in routine #2",cr pause 1000 goto routine3 routine1: debug "we're in routine #1",cr pause 1000 goto routine2 routine3: debug "we're in routine #3",cr pause 1000 goto routine1
5: basic stamp command reference ? high basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 215 high bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px bs2px high pin function make the specified pin output high.  pin is a variable/constant/expression (0 ? 15) that specifies which i/o pin to set high. this pin will be placed into output mode. quick facts table 5.31: high quick facts. bs1 and all bs2 models related commands low and toggle explanation the high command sets the specified pin to 1 (a +5 volt level) and then sets its mode to output. for example, high 6 does exactly the same thing as: out6 = 1 dir6 = 1 using the high command is faster and more concise, in this case. connect an led and a resistor as shown in figure 5.7 for demo program high.bs2, below. figure 5.7: example led circuit. p0 470 ? led vss note: expressions are not allowed as arguments on the bs1. the range of the pin argument on the bs1 is 0 ? 7. 1 1 a ll 2 all 2
high ? basic stamp command reference page 216 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com demo program (high.bs2) ' high.bs2 ' this simple program sets i/o pin 0 high for 1/2 second and low for ' 1/2 second in an endless loop. connect an led to p0 for a simple ' blinker. ' {$stamp bs2} main: high 0 pause 500 low 0 pause 500 goto main end 1 a ll 2 note: this is written for the bs2 but can be used for the bs1 and all other bs2 models as well, by modifying the $stamp directive accordingly.
5: basic stamp command reference ? i2cin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 217 i2cin bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px i2cin pin, slaveid, { address { \ lowaddress }, } [ inputdata ] function receive data from a device using the i 2 c protocol.  pin is a variable/constant/expression (0 or 8) that specifies which i/o pins to use. i 2 c devices require two i/o pins to communicate. the pin argument serves a double purpose; specifying the first pin (for connection to the chip's sda pin) and, indirectly, the other required pin (for connection to the chip's scl pin). see explanation below. both i/o pins will be toggled between output and input mode during the i2cin command and both will be set to input mode by the end of the i2cin command.  slaveid is a variable/constant/expression (0 ? 255) indicating the unique id of the i 2 c chip.  address is an optional variable/constant/expression (0 ? 255) indicating the desired address within the i 2 c chip to receive data from. the address argument may be used with the optional lowaddress argument to indicate a wo rd-sized address value.  lowaddress is an optional variable/constant/expression (0 ? 255) indicating the low-byte of the word-sized address within the i 2 c chip to receive data from. this argument must be used along with the address argument.  inputdata is a list of variables and modifiers that tells i2cin what to do with incoming data. i2cin can store data in a variable or array, interpret numeric text (decimal, binary, or hex) and store the corresponding value in a variable , wait for a fixed or variable sequence of bytes, or ignore a specified number of bytes. these actions can be combined in any order in the inputdata list.
i2cin ? basic stamp command reference page 218 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com quick facts bs2p, bs2pe, and bs2px values for pin pin = 0 pin = 8 i/o pin arrangement 0: serial data (sda) pin 1: serial clock (scl) pin 8: serial data (sda) pin 9: serial clock (scl) pin transmission rate approximately 81 kbits/sec on a bs2p, 45 kbits/sec on a bs2pe, and 83 kbits/sec on a bs2px (not including overhead). special notes both the sda and scl pins must have 1 k ? - 4.7 k ? pull-up resistors. the i2cin command does not allow for multiple masters. the basic stamp cannot operate as an i 2 c slave device. related command i2cout table 5.32: i2cin quick facts. explanation the i 2 c protocol is a form of synchronous serial communication developed by phillips semiconductors. it only requires two i/o pins and both pins can be shared between multiple i 2 c devices. the i2cin command allows the basic stamp to receive data from an i 2 c device. the following is an example of the i2cin command: result var byte i2cin 0, $a1, 0, [result] this code will transmit a "read" command to an i 2 c device (connected to i/o pins 0 and 1) and then will receive one byte and store it in the variable result. though it may seem strange, the i2cin command first transmits some data and then receives data. it must first transmit information (id, read/write and address) in order to tell the i 2 c device what information it would like to receive. the exact in formation transmitted ($a1, 0) depends on the i 2 c device that is being used. the above example will read a byte of data from location 0 of a 24lc16b eeprom from microchip. figure 5.8 shows the proper wiring for this example to work. the slaveid argument ($a1) is both the id of the chip and the command to read from the chip; the 1 means read. the address argument (0) is the eeprom location to read from. a simple i2cin example . note: the i2c command will make up to 8 attempts to connect to the addressed device. if the device does not properly respond, the i2c command will timeout and the inputdata will remain unchanged..
5: basic stamp command reference ? i2cin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 219 figure 5.8: example circuit for the i2cin command and a 24lc16b eeprom. note: the 4.7 k ? resistors are required for the i2cin command to function properly. vss p1 vdd 4.7 k ? p0 24lc16b (dip) 4.7 k ? sda scl 1 2 3 4 8 7 6 5 the i2cin command's inputdata argument is similar to the serin command's inputdata argument. this means data can be received as ascii character values, decimal, hexadecimal and binary translations and string data as in the examples be low. (assume the 24lc16b eeprom is used and it has the string, "value: 3a: 101" stored, starting at location 0). value var byte(13) i2cin 0, $a1, 0, [value] ' receive the ascii value for "v" i2cin 0, $a1, 0, [dec value] ' receive the number 3 i2cin 0, $a1, 0, [hex value] ' receive the number $3a i2cin 0, $a1, 0, [bin value] ' receive the number %101 i2cin 0, $a1, 0, [str value\13] ' receive the string "value: 3a:101" table 5.33 and table 5.34 below list all the available special formatters and conversion formatters available to the i2cin command. see the serin command for additional information and examples of their use. table 5.33: i2cin special formatters. special formatter action skip length ignore length bytes of characters. spstr l input a character stream of length l bytes (up to 126) into scratch pad ram, starting at location 0. use get to retrieve the characters. str bytearray \l {\e} input a character string of length l into an array. if specified, an end character e causes the string input to end before reaching length l. remaining byte s are filled with 0s (zeros). waitstr bytearray {\l} wait for a sequence of bytes matching a string stored in an array variable, optionally limited to l characters. if the optional l argument is left off, the end of the array-string must be marked by a byte containing a zero (0). r eceiving formatted data .
i2cin ? basic stamp command reference page 220 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com conversion formatter type of number numeric characters accepted notes dec{1..5} decimal, optionally limited to 1 ? 5 digits 0 through 9 1 sdec{1..5} signed decimal, optionally limited to 1 ? 5 digits -, 0 through 9 1,2 hex{1..4} hexadecimal, optionally lim ited to 1 ? 4 digits 0 through 9, a through f 1,3,5 shex{1..4} signed hexadecimal, optionally limited to 1 ? 4 digits -, 0 through 9, a through f 1,2,3 ihex{1..4} indicated hexadecimal, optionally limited to 1 ? 4 digits $, 0 through 9, a through f 1,3,4 ishex{1..4} signed, indicated hexadecimal, optionally limited to 1 ? 4 digits -, $, 0 through 9, a through f 1,2,3,4 bin{1..16} binary, optionally limited to 1 ? 16 digits 0, 1 1 sbin{1..16} signed binary, optionally limited to 1 ? 16 digits -, 0, 1 1,2 ibin{1..16} indicated binary, optionally limited to 1 ? 16 digits %, 0, 1 1,4 isbin{1..16} signed, indicated binary, optionally limited to 1 ? 16 digits -, %, 0, 1 1,2,4 num generic numeric input (decimal, hexadecimal or binary); hexadeci mal or binary number must be indicated $, %, 0 through 9, a through f 1, 3, 4 snum similar to num with value treated as signed with range -32768 to +32767 -, $, %, 0 through 9, a through f 1,2,3,4 table 5.34: i2cin conversion formatters. 1 all numeric conversions will continue to accept new data until receiving either the specified number of digits (ex: three digits fo r dec3) or a non-numeric character. 2 to be recognized as part of a number, the minus sign (-) must immediately precede a numeric character. the minus sign character occurring in non-numeric text is ignored and any character (including a space) between a minus and a number causes the minus to be ignored. 3 the hexadecimal formatters are not case-sensi tive; ?a? through ?f? means the same as ?a? through ?f?. 4 indicated hexadecimal and binary formatters ignore all characters, even valid numerics, until they receive the appropriate prefix ($ fo r hexadecimal, % for bi nary). the indicated formatters can differentiate between text and hexadecimal (ex: abc would be interpreted by hex as a number but ihex would ignore it unless expressed as $abc). likewise, the binary version can dist inguish the decimal number 10 fr om the binary number %10. a prefix occurring in non-numeric text is i gnored, and any character (including a space) between a prefix and a number causes the prefix to be ignored. indicated, signed formatters require that the minus sign come before the prefix, as in -$1b45. 5 the hex modifier can be used for decimal to bcd conversion. see ?hex to bcd conversion? on page 97. for examples of all conversion formatters and how they process incoming data, see appendix c.
5: basic stamp command reference ? i2cin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 221 the i 2 c protocol has a well-def ined standard for the information passed at the start of each transmission. first of all, any information sent must be transmitted in units of 1 byte (8-b its). the first byte, we call the slaveid , is an 8-bit pattern whose upper 7-bits co ntain the unique id of the device you wish to communicate with. the lo west bit indicates whether this is a write operation (0) or a read operation (1). figure 5.9 shows this format. figure 5.9: slave id format. 7 a 6 6 a 5 5 a 4 4 a 3 3 a 2 2 a 1 1 a 0 0 r/w the second byte, immediately follow ing the slaveid, is the optional address . it indicates the 8-bit address (within the device) containing the data you would like to receive. note that the address argument is optional and may be left unspecified for devices that don't require an address argument. some devices require more than 8 bits of address. for this case, the optional lowaddress argument can be used for the low-byte of the required address. when using the lowaddress argument, the address argument is effectively the high-byte of the address value. for example, if the entire address value is 2050, use 8 for the address argument and 2 for the lowaddress argument (8 * 256 + 2 = 2050). following the last address byte is the first byte of data. this data byte may be transmitted or received by the basic stamp. in the case of the i2cin command, this data byte is transmitte d by the device and received by the basic stamp. additionally, multiple data bytes can follow the address, depending on the i 2 c device. note that every device has different limitations regarding how may contiguous bytes they can receive or transmit in one session. be aware of these device limitations and program accordingly. every i 2 c transmission session begins with a start condition and ends with a stop condition. additionally, immediately after every byte is transmitted, an extra clock cycle is used to send or receive an acknowledgment signal (ack). all of these operations are automatically taken care of by the i2cin command so that you need not be concerned with them. the general i 2 c transmission format is shown in figure 5.10. t he i 2 c protocol format . u sing l ong addresses . s tart and s top c onditions and a cknowledgments .
i2cin ? basic stamp command reference page 222 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com s p s t a r t slaveid a c k address a c k data a c k s t o p b u s f r e e a 6 a 5 a 4 a 3 a 2 a 1 a 0 rw a 6 a 5 a 4 a 3 a 2 a 1 a 0 a 7 d 6 d 5 d 4 d 3 d 2 d 1 d 0 d 7 notes: s = start condition p = stop condition a = id or address bit d = data bit (transmitted by the basic stamp or the i c device) ack = acknowledge signal. (most acknowledge signals are generated by the i c device) 2 2 figure 5.10: i 2 c transmission format. since the i2cin command is intended for input only, it actually overrides the "r/w" bit (bit 0) in the slaveid argument. this is done so that it can use the i 2 c protocol's "combined format" for receiving data. put simply, this means a command such as: i2cin 0, $a1, 10, [result] actually transmits $a0, then 10, then $a1 and then it reads the data back from the device. the $a0 means "write", the 10 is the address to write to, and finally, the $a1 indicates a change of direction; to "read" the location, instead. even though the i2cin co mmand really doesn't care what the value of the slaveid 's lsb is, it is suggested that you still set it appropriately for clarity. also note that the i2cin command does not support multiple i 2 c masters and the basic stamp cannot operate as an i 2 c slave device. demo program (i2c.bsp) ' i2c.bsp ' this program demonstrates writing and reading every location in a 24lc16b ' eeprom using the bs2p/bs2pe's i2c commands. connect the bs2p, bs2pe, or ' bs2px to the 24lc16b dip eeprom as shown in the diagram in the i2cin or ' i2cout command description. ' {$stamp bs2p} ' {$pbasic 2.5} #if ($stamp < bs2p) #then #error "program requires bs2p, bs2pe, or bs2px." #endif sda pin 0 ' i2c sda pin scl pin sda + 1 s pecial note about i2cin inplimentation . note: this example program can be used with the bs2p, bs2pe, and bs2px. this program uses conditional compilation techniques; see chapter 3 for more information.
5: basic stamp command reference ? i2cin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 223 addr var word ' internal address block var nib ' block address in 24lc16 value var byte ' value to write check var nib ' for checking retuned values result var byte(16) ' array for returned value write_to_eeprom: debug "writing...", cr pause 2000 for addr = 0 to 2047 step 16 ' loop through all addresses block = addr.nib2 << 1 ' calculate block address value = addr >> 4 ' create value from upper 8 bits ' write 16 bytes i2cout sda, $a0 | block, addr, [rep value\16] pause 5 debug "addr: ", dec4 addr, "-", dec4 addr + 15, " ", "value: ", dec3 value, cr next pause 2000 read_from_eeprom: debug cr, "reading...", cr pause 2000 for addr = 0 to 2047 step 16 block = addr.nib2 << 1 value = addr >> 4 i2cin sda, $a1 | block, addr, [str result\16] for check = 0 to 15 if (result(check) <> value) then error next debug "addr: ", dec4 addr, "-", dec4 addr + 15, " ", "value: ", dec3 result, cr next pause 100 debug cr, "all locations passed" end error: debug "error at location: ", dec4 addr + check, cr, "found: ", dec3 result(check), ", expected: ", dec3 value end
i2cin ? basic stamp command reference page 224 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? i2cout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 225 i2cout bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px i2cout pin, slaveid, { address { \ lowaddress } , } [ outputdata ] function send data to a device using the i 2 c protocol.  pin is a variable/constant/expression (0 or 8) that specifies which i/o pins to use. i 2 c devices require two i/o pins to communicate. the pin argument serves a double purpose; specifying the first pin (for connection to the chip's sda pin) and, indirectly, the other required pin (for connection to the chip's scl pin). see explanation below. both i/o pins will be toggled between output and input mode during the i2cout command and both will be set to input mode by the end of the i2cout command.  slaveid is a variable/constant/expression (0 ? 255) indicating the unique id of the i 2 c chip.  address is an optional variable/constant/expression (0 ? 255) indicating the desired address within the i 2 c chip to send data to. the address argument may be used with the optional lowaddress argument to indicate a word -sized address value.  lowaddress is an optional variable/constant/expression (0 ? 255) indicating the low-byte of the word-sized address within the i 2 c chip to receive data from. this argument must be used along with the address argument.  outputdata is a list of variables, constants, expressions and formatters that tells i2cout how to format outgoing data. i2cout can transmit individual or repeating bytes, convert values into decimal, hexadecimal or binary te xt representations, or transmit strings of bytes from variable arrays. these actions can be combined in any order in the outputdata list.
i2cout ? basic stamp command reference page 226 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com quick facts bs2p, bs2pe, and bs2px values for pin pin = 0 pin = 8 i/o pin arrangement 0: serial data (sda) pin 1: serial clock (scl) pin 8: serial data (sda) pin 9: serial clock (scl) pin transmission rate approximately 81 kbits/sec on a bs2p, 45 kbits/sec on a bs2pe, and 83 kbits/sec on a bs2px (not including overhead). special notes the sda and scl pins must have 1 k ? - 4.7 k ? pull-up resistors. the i2cin command does not allow for multiple masters. the basic stamp cannot operate as an i 2 c slave device. related command i2cin table 5.35: i2cout quick facts. explanation the i 2 c protocol is a form of synchronous serial communication developed by phillips semiconductors. it only requires two i/o pins and both pins can be shared between multiple i 2 c devices. the i2cout command allows the basic stamp to send data to an i 2 c device. the following is an example of the i2cout command: i2cout 0, $a0, 5, [100] this code will transmit a "write" command to an i 2 c device (connected to i/o pins 0 and 1), followed by an address of 5 and finally will transmit the number 100 . the above example will write a byte of data to location 5 of a 24lc16b eeprom from microchip. figure 5.11 shows the proper wiring for this example to work. the slaveid argument ($a0) is both the id of the chip and the command to write to the chip; the 0 means write. the address argument (5) is the eeprom location to write to. vss p1 vdd 4.7 k ? p0 24lc16b (dip) 4.7 k ? sda scl 1 2 3 4 8 7 6 5 figure 5.11: example circuit for the i2cout command and a 24lc16b eeprom. note: the 4.7 k ? resistors are required for the i2cout command to function properly. a simple i2cout example .
5: basic stamp command reference ? i2cout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 227 the i2cout command's outputdata argument is similar to the debug and serout command's outputdata argument. this means data can be sent as literal text, ascii character values, repetitive values, decimal, hexadecimal and binary translations and string data as in the examples below. (assume the 24lc16b eeprom is being used). value var byte value = 65 i2cout 0, $a0, 0, [value] ' send "a" i2cout 0, $a0, 0, [rep value\5] ' send "aaaaa" i2cout 0, $a0, 0, [dec value] ' send "6" and "5" i2cout 0, $a0, 0, [hex value] ' send "4" and "1" i2cout 0, $a0, 0, [bin value] ' send "1000001" table 5.36 and table 5.37 list all the available formatters for the i2cout command. see the debug and serout commands for additional information and examples of their use. table 5.36: i2cout conversion formatters. conversion formatter type of number notes dec{1..5} decimal, optionally fixed to 1 ? 5 digits 1 sdec{1..5} signed decimal, optionally fixed to 1 ? 5 digits 1,2 hex{1..4} hexadecimal, optionally fixed to 1 ? 4 digits 1,3 shex{1..4} signed hexadecimal, optionally fixed to 1 ? 4 digits 1,2 ihex{1..4} indicated hexadecimal, optionally fixed to 1 ? 4 digits ($ prefix) 1 ishex{1..4} signed, indicated hexadecimal, opti onally fixed to 1 ? 4 digits ($ prefix) 1,2 bin{1..16} binary, optionally fixed to 1 ? 16 digits 1 sbin{1..16} signed binary, optionally fixed to 1 ? 16 digits 1,2 ibin{1..16} indicated binary, optionally fixed to 1 ? 16 digits (% prefix) 1 isbin{1..16} signed, indicated binary, optiona lly fixed to 1 ? 16 digits (% prefix) 1,2 1 fixed-digit formatters like dec4 will pad t he number with leading 0s if necessary; ex: dec4 65 sends 0065. if a number is larg er than the specified number of digits, the leading digits will be dropped; ex: dec4 56422 sends 6422. 2 signed modifiers work under two's complement rules. 3 the hex modifier can be used for bcd to decimal conversion. see ?hex to bcd conversion? on page 97. s ending and formatting data .
i2cout ? basic stamp command reference page 228 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com special formatter action ? displays "symbol = x' + carriage return; where x is a number. default format is decimal, but may be combined with conversion formatters (ex: bin ? x to display "x = binary_number"). asc ? displays "symbol = 'x'" + carriage return; where x is an ascii character. str bytearray {\l} send character string from an arra y. the optional \l argument can be used to limit the output to l characters, otherwise, characters will be sent up to the first byte equal to 0 or the end of ram space is reached. rep byte \l send a string consisting of byte repeated l times (ex: rep "x"\10 sends "xxxxxxxxxx"). table 5.37: i2cout special formatters the i 2 c protocol has a well-def ined standard for the information passed at the start of each transmission. first of all, any information sent must be transmitted in units of 1 byte (8-b its). the first byte, we call the slaveid , is an 8-bit pattern whose upper 7-bits co ntain the unique id of the device you wish to communicate with. the lo west bit indicates whether this is a write operation (0) or a read operation (1). figure 5.12 shows this format. 7 a 6 6 a 5 5 a 4 4 a 3 3 a 2 2 a 1 1 a 0 0 r/w figure 5.12: slave id format the second byte, immediately following the slaveid , is the optional address. it indicates the 8-bit address (w ithin the device) containing the data you would like to receive. note that the address argument is optional and may be left unspecified for devices that don't require an address argument. some devices require more than 8 bits of address. for this case, the optional lowaddress argument can be used for the low-byte of the required address. when using the lowaddress argument, the address argument is effectively the high-byte of the address value. for example, if the entire address value is 2050, use 8 for the address argument and 2 for the lowaddress argument (8 * 256 + 2 = 2050). following the last address byte is the first byte of data. this data byte may be transmitted or received by the basi c stamp. in the case of the i2cout command, this data byte is transmi tted by the basic stamp and received by the device. additionally, multiple data bytes can follow the address, t he i 2 c protocol format . u sing l ong addresses .
5: basic stamp command reference ? i2cout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 229 depending on the i 2 c device. note that every device has different limitations regarding how may contiguous bytes they can receive or transmit in one session. be aware of this, and program accordingly. every i 2 c transmission session begins with a start condition and ends with a stop condition. additionally, immediately after every byte is transmitted, an extra clock cycle is used to send or receive an acknowledgment signal (ack). all of these operations are automatically taken care of by the i2cout command so that you need not be concerned with them. the general i 2 c transmission format is shown in figure 5.13. figure 5.13: i 2 c transmission format s p s t a r t slaveid a c k address a c k data a c k s t o p b u s f r e e a 6 a 5 a 4 a 3 a 2 a 1 a 0 rw a 6 a 5 a 4 a 3 a 2 a 1 a 0 a 7 d 6 d 5 d 4 d 3 d 2 d 1 d 0 d 7 notes: s = start condition p = stop condition a = id or address bit d = data bit (transmitted by the basic stamp or the i c device) ack = acknowledge signal. (most acknowledge signals are generated by the i c device) 2 2 since the i2cout command is intended for output only, it actually overrides the "r/w" bit (bit 0) in the slaveid argument. this is done to avoid device conflicts should the value be mistyped. put simply, this means commands such as: i2cout 0, $a0, 10, [0] and i2cout 0, $a1, 10, [0] both transmit the same thing ($a0, then 10, then the data). even though the i2cout command really doesn't care what the value of the slaveid 's lsb is, it is suggested that you st ill set it appropriately for clarity. also note that the i2cout command does not support multiple i 2 c masters and the basic stamp cannot operate as an i 2 c slave device. demo program (i2c.bsp) ' i2c.bsp ' this program demonstrates writing and reading every location in a 24lc16b ' eeprom using the bs2p/bs2pe's i2c commands. connect the bs2p, bs2pe, or ' bs2px to the 24lc16b dip eeprom as shown in the diagram in the i2cin or s pecial note about i2cout inplimentation . s tart and s top c onditions and a cknowledgments . note: this example program can be used with the bs2p, bs2pe and bs2px. this program uses conditional compilation techniques; see chapter 3 .
i2cout ? basic stamp command reference page 230 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com ' i2cout command description. ' {$stamp bs2p} ' {$pbasic 2.5} #if ($stamp < bs2p) #then #error "program requires bs2p, bs2pe or bs2px." #endif sda pin 0 ' i2c sda pin scl pin sda + 1 addr var word ' internal address block var nib ' block address in 24lc16 value var byte ' value to write check var nib ' for checking retuned values result var byte(16) ' array for returned value write_to_eeprom: debug "writing...", cr pause 2000 for addr = 0 to 2047 step 16 ' loop through all addresses block = addr.nib2 << 1 ' calculate block address value = addr >> 4 ' create value from upper 8 bits ' write 16 bytes i2cout sda, $a0 | block, addr, [rep value\16] pause 5 debug "addr: ", dec4 addr, "-", dec4 addr + 15, " ", "value: ", dec3 value, cr next pause 2000 read_from_eeprom: debug cr, "reading...", cr pause 2000 for addr = 0 to 2047 step 16 block = addr.nib2 << 1 value = addr >> 4 i2cin sda, $a1 | block, addr, [str result\16] for check = 0 to 15 if (result(check) <> value) then error next debug "addr: ", dec4 addr, "-", dec4 addr + 15, " ", "value: ", dec3 result, cr next pause 100 debug cr, "all locations passed" end error: debug "error at location: ", dec4 addr + check, cr, "found: ", dec3 result(check), ", expected: ", dec3 value end
5: basic stamp command reference ? if...then basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 231 if?then bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px if condition(s) then address if condition(s) then statement(s) { else statement(s) } if condition(s) then statement(s) { elseif condition(s) then statement(s)? } { else statement(s) } endif function evaluate condition(s) and, if true, go to the address or execute the statement(s) following then, otherwise process the elseif/else block(s), if provided. elseif is optional and works just like if, but is only evaluated if the condition(s) in the preceding if is false. the else block is optional and is executed if all condition(s) in all preceding if/elseifs are false. the program will continue at the next line of code (single-line syntax) or the line that follows endif (multi-line syntax) unless address or statement(s) are executed that cause the program to jump.  condition is a statement, such as ?x = 7? that can be evaluated as true or false. condition can be a very simple or very complex relationship, as described below.  address is a label that specifies where to go in the event that condition(s) is true.  statement is any valid pbasic instruction. multiple statements may be placed on the same line (though not recommended) by separating each statement with a colon ( : ). all 2 note: pbasic 1.0 and pbasic 2.0 only support if condition(s) then address . pbasic 2.5 supports all syntax variations. 1 a ll 2 all 2
if?then ? basic stamp command reference page 232 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com quick facts bs1 all bs2 models comparison operators =, <>, >, <, >=, <= =, <>, >, <, >=, <= conditional logic operators and, or not, and, or, xor format of condition variable comparison value ; where value is a variable or constant value1 comparison value2 ; where value1 and value2 can by any of variable, constant or expression parentheses not allowed allowed max nested if?thens n/a 16 max elseifs per if n/a 16 max elses per if n/a 1 related command none select?case table 5.38: if...then quick facts. explanation if...then is pbasic's decision maker that allows one block of code or another to run based on the value (t rue or false) of a condition. the condition that if...then tests is written as a mixture of comparison and logic operators. the available comparison operators are: comparison operator symbol definition = equal <> not equal > greater than < less than >= greater than or equal to <= less than or equal to table 5.39: if...then comparison operators. comparisons are always written in the form: value1 comparison value2. the values to be compared can be any combination of variables (any size), constants, or expressions. the following example is an if?then command with a simple condition: if value < 4000 then main this code will compare the value of value to the number 4000. if value is less than 4000, the condition is true and the program will jump (implied note: on the bs1, expressions are not allowed as arguments. also, the value1 (to the left of comparison) must be a variable. 1 a simple form of if?then 1 a ll 2
5: basic stamp command reference ? if...then basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 233 goto) to the label called main . this is the simplest form of if?then and is the only form supported by pbasic 1.0 and pbasic 2.0. the condition(s) argument is very powerful and flexible. in the next few pages we?ll demonstrate this flexibility in great detail and afterwards we?ll discuss the additional, optional arguments allowed by pbasic 2.5. here's a complete example of if...then in action: value var word main: pulsin 0, 1, value debug dec value, cr if value < 4000 then main debug "pulse value was greater than 3999!" here, the basic stamp will look for and measure a pulse on i/o pin 0, then compare the result, value , against 4000. if value is less than (<) 4000, it will jump back to main . each time through the loop, it displays the measured value and once it is greater than or equal to 4000, it displays, "value was greater than 3999!" on all bs2 models, the values can be expressions as well. this leads to very flexible and sophisticated comparisons. the if?then statement below is functionally the same as the one in the program above: if value < (45 * 100 ? (25 * 20)) then val_low here the basic stamp evaluates the expression: 45 * 100 = 4500, 25 * 20 = 500, and 4500 ? 500 = 4000. then the basic stamp performs the comparison: is value < 4000? another example that is functionally the same: if (value / 100) < 40 then val_low it's important to realize that all comparisons are performed using unsigned, 16-bit math. this can lead to strange results if you mix signed and unsigned numbers in if...then conditions. watch what happens here when we include a signed number (?99): w atch out for unsigned math comparison errors all 2 all 2 all 2 a ll a bout c ondition ( s ) . note: for bs1's, change line 1 to symbol value = w0 and line 4 to debug #value, cr
if?then ? basic stamp command reference page 234 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com test: if -99 < 100 then is_less debug "greater than or equal to 100" end is_less: debug "less than 100" end although ?99 is obviously less than 100, the program will say it is greater. the problem is that ?99 is internally represented as the two?s complement value 65437, which (using unsigned math) is greater than 100. this phenomena will occur whether or not the negative value is a constant, variable or expression. if...then supports the conditional lo gic operators not, and, or, and xor to allow for more sophisticated conditions, such as multi-part conditions. see table 5.38 for a list of the operators and table 5.40 for their effects. the not operator inverts the outcome of a condition, changing false to true, and true to false. the following if...thens are equivalent: if x <> 100 then not_equal if not x = 100 then not_equal the operators and, or, and xor can be used to join the results of two conditions to produce a single true /false result. and and or work the same as they do in everyday speech. run the example below once with and (as shown) and again, substituting or for and: value1 var byte value2 var byte setup: value1 = 5 value2 = 9 main: if value1 = 5 and value2 = 10 then is_true debug "statement is false" end is_true: debug "statement is true" end note: for bs1's, change lines1 and 2 to: symbol value1 = b2 symbol value2 = b3 l ogical o perators (not, and, or and xor). note: the not and xor operators are not available on the bs1. 1
5: basic stamp command reference ? if...then basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 235 the condition ?value1 = 5 and value2 = 10? is not true. although value1 is 5, value2 is not 10. the and operator works just as it does in english; both conditions must be true for the st atement to be true. the or operator also works in a familiar way; if one or the other or both conditions are true, then the statement is true. th e xor operator (short for exclusive- or) may not be familiar, but it does have an english counterpart: if one condition or the other (but not both) is true, then the statement is true. table 5.40 below summarizes the effects of the conditional logic operators. on all bs2 models you can alter the order in which comparisons and logical operations are performed by using parentheses. operations are normally evaluated left-to-right. putti ng parentheses around an operation forces pbasic 2.0 and pbasic 2.5 to evaluate it before operations that are not in parentheses. table 5.40: conditional logic operators truth tables. note: the not and xor operators are not available on the bs1. truth table for logical operator: not condition a not a false true true false truth table for logical operator: and condition a condition b a and b false false false false true false true false false true true true truth table for logical operator: or condition a condition b a or b false false false false true true true false true true true true truth table for logical operator: xor condition a condition b a xor b false false false false true true true false true true true false 1 note: on the bs1, parentheses are not allowed within arguments. 1
if?then ? basic stamp command reference page 236 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com internally, the basic stamp defines ?false? as 0 and ?true? as any value other than 0. consider the following instructions: flag var bit setup: flag = 1 test: if flag then is_true debug "false" end is_true: debug "true" end since flag is 1, if...then would evaluate it as true and print the message ?true? on the screen. suppose yo u changed the if...then command to read ?if not flag then is_true.? that would also evaluate as true. whoa! isn?t not 1 the same thing as 0? no, at least not in the 16-bit world of the basic stamp. internally, the basic stamp sees a bit variable containing 1 as the 16-bit number %0000000000000001. so it sees the not of that as %1111111111111110. since any non-zero number is regarded as true, not 1 is true. strange but true. the easiest way to avoid the kinds of problems this might cause is to always use a conditional operator with if...then. change the example above to read if flag = 1 then is_true. the result of the comparison will follow if...then rules. also, the logical operators will work as they should; if not flag = 1 then is_true will correctly evaluate to false when flag contains 1. this also means that you should on ly use the "named" conditional logic operators not, and, or, and xor with if...then. the conditional logic operators format their results corr ectly for if...then instructions. the other logical operators, represented by sy mbols ~, &, |, and ^ do not; they are binary logic operators. the remainder of this discussion on ly applies to the extended if?then syntax supported by pbasic 2.5. i nternal representation of b oolean values (t rue vs . f alse ). a voiding errors with b oolean results . all 2 all 2
5: basic stamp command reference ? if...then basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 237 in addition to supporting everythi ng discussed above, pbasic 2.5 provides enhancements to the if?then command that allow for more powerful, structured programming. in prior examples we?ve only used the first syntax form of this command: if condition(s) then address . that form, while handy in some situations, can be quite limiting in others. for example, it is common to need to perform a single instruction based on a condition. take a look at the following code: ' {$pbasic 2.5} x var byte for x = 1 to 20 ' count to 20 debug cr, dec x ' display num if (x // 2) = 0 then debug " even" ' even num? next this example prints the numbers 1 through 20 on the screen but every even number is also marked with the text ? even.? the if?then command checks to see if x is even or odd and, if it is even (i.e.: x // 2 = 0), then it executes the statement to the right of then: debug ? even.? if it was odd, it simply continued at the following line, next. suppose you also wanted to mark the odd numbers. you could take advantage of the optional else clause, as in: ' {$pbasic 2.5} x var byte for x = 1 to 20 ' count to 20 debug cr, dec x if (x // 2) = 0 then debug " even" else debug ? odd? next this example prints the numbers 1 through 20 with ? even? or ? odd? to the right of each number. for each number (each time through the loop) if?then asks the question, ?is th e number even?? and if it is it executes debug ? even? (the instructio n after then) or, if it is not even it executes debug ? odd? (the instruct ion after else). it?s important to note that this form of if?then always executes code as a result of condition(s) ; it either does ?this? (then) or ?that? (else). if?then with a s ingle s tatement
if?then ? basic stamp command reference page 238 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the if?then in the previous example is called a ?single-line? syntax. it is most useful where you only have one instruction to run as the result of a condition . sometimes this form may be a little hard to read, like in our above example. for these cases, it wo uld be better to use the ?multi-line? syntax of if?then. the multi-line fo rmat allows the same flexibility as the single-line format, but is easier to read in most cases and requires an endif statement at the end. fo r example, our if?then line above could be re-written as: if (x // 2) = 0 then debug " even" ' even number else debug " odd" ' odd number endif this example runs exactly the same way, is much easier to read and also leaves extra room to add some help ful comments on the right. we also indented the statement(s) for clarity and suggest you do the same. did you notice that multi-line syntax requires endif to mark the end of the if?then?else construct? that is because the statement(s) argument can be multiple instructions on multiple lines, so without endif there is no way to know just where the if?then?else ends. occasionally, it may be necessary to have compound if statements. one way to achieve this is through ne sted if?then?end constructs: ' {$pbasic 2.5} value var word do pulsin 0, 1, value ' measure pulse input debug dec value, cr if (value > 4000) then ' evaluate duration debug "value was greater than 4000" else if (value = 4000) then debug "value was equal to 4000" else debug "value was less than 4000" endif endif debug cr, cr pause 1000 loop s ingle - line vs . m ulti -l ine if?then s n ested if?then s
5: basic stamp command reference ? if...then basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 239 here, the basic stamp will look for and measure a pulse on i/o pin 0, then compare the result, value , against 4000. based on this comparison, a message regarding the pulse width value will be printed. if value is greater than 4000, ?value was greater than 4000? is printed to the screen. look what happens if value is not greater than 4000? the code in the else block is run, which is another if?then?else statement. this ?nested? if?then statement checks if value is equal to 4000 and if it is, it prints ?value was equal to 4000? or, if it was not equal, the last else code block executes, printing ?value wa s less than 4000.? up to sixteen (16) if?thens can be nested like this. the nesting option is great for many situations, but, like single-line syntax, may be a little hard to read, especially if there are multiple nested statements or there is more than one instruction in each of the statement(s) arguments. additionally, every mult i-line if?then construct must end with endif, resulting in two endifs right near each other in our example; one for the innermost if?then and one for the outermost if?then. for this reason, if?then supports an optional elseif clause. the elseif clause takes the place of a nested if?then and removes the need for multiple endifs . our if?then construction from the example above could be rewritten to: ' {$pbasic 2.5} if (value > 4000) then ' evaluate duration debug "value was greater than 4000" elseif (value = 4000) then debug "value was equal to 4000" else debug "value was less than 4000" endif this if?then construct does the same thing as in the previous example: 1) if value is greater than 4000: it displays ?value was greater than 4000? 2) else, if value is equal to 4000 (the elseif part): it displays ?value was equal to 4000? 3) and finally (else) if none of the above were true: it displays ?value was less than 4000? u sing the elseif clause
if?then ? basic stamp command reference page 240 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com note that an if?then construct can ha ve as many as sixteen (16) elseif clauses, but a maximum of only one (1) else clause. there are three demo programs below. the first two demonstrate the pbasic 1.0 (bs1) and pbasic 2.0 (all bs2 models) form of the if?then command. the last example demonstrates the pbasic 2.5 (all bs2 models) form of if?then. demo program (if-then.bs1) ' if-then.bs1 ' the program below generates a series of 16-bit random numbers and tests ' each to determine whether they're evenly divisible by 3. if a number is ' evenly divisible by 3, then it is printed, otherwise, the program ' generates another random number. the program counts how many numbers it ' prints, and quits when this number reaches 10. ' {$stamp bs1} ' {$pbasic 1.0} symbol sample = w0 ' random number to be tested symbol samps = b2 ' number of samples taken symbol temp = b3 ' temporary workspace setup: sample = 11500 mult3: random sample ' put a random number into sample temp = sample // 3 if temp <> 0 then mult3 ' not multiple of 3? -- try again debug #sample, "divides by 3", cr ' show sample divisible by 3 samps = samps + 1 ' count multiples of 3 if samps = 10 then done ' quit with 10 samples goto mult3 ' keep checking done: debug cr, "all done." end demo program (if-then.bs2) ' if-then.bs2 ' the program below generates a series of 16-bit random numbers and tests ' each to determine whether they're evenly divisible by 3. if a number is ' evenly divisible by 3, then it is printed, otherwise, the program ' generates another random number. the program counts how many numbers it ' prints, and quits when this number reaches 10. 1 all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? if...then basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 241 ' {$stamp bs2} ' {$pbasic 2.0} sample var word ' random number to be tested samps var nib ' number of samples taken temp var nib ' temporary workspace setup: sample = 11500 mult3: random sample ' put a random number into sample temp = sample // 3 if temp <> 0 then mult3 ' not multiple of 3? -- try again debug dec5 sample, " divides by 3", cr samps = samps + 1 ' count multiples of 3 if samps = 10 then done ' quit with 10 samples goto mult3 ' keep checking done: debug cr, "all done." end demo program (if-then-else.bs2) ' if-then-else.bs2 ' the program below generates a series of 16-bit random numbers and tests ' each to determine whether they're evenly divisible by 3. if a number is ' evenly divisible by 3, then it is printed, otherwise, the program ' generates another random number. the program counts how many numbers it ' prints, and quits when this number reaches 10. ' {$stamp bs2} ' {$pbasic 2.5} ' version 2.5 required sample var word ' random number to be tested hits var nib ' number of hits misses var word ' number of misses setup: sample = 11500 main: do random sample ' put a random number into sample if ((sample // 3) = 0) then ' divisible by 3? debug dec5 sample, ' - yes, print value and message " is divisible by 3", cr all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
if?then ? basic stamp command reference page 242 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com hits = hits + 1 ' count hits (divisible by 3) else misses = misses + 1 ' count misses endif loop until (hits = 10) ' quit after 10 hits debug cr, "all done.", cr, cr, ' display results "hits: ", dec hits, cr, "misses: ", dec misses, cr, "samples: ", dec (hits + misses) end
5: basic stamp command reference ? input basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 243 input bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px input pin function make the specified pin an input.  pin is a variable/constant/expression (0 ? 15) that specifies which i/o pin to set to input mode. quick facts table 5.41: input quick facts. bs1 all bs2 models input pin variables pins; pin0 through pin7 ins; in0 through in15 related commands output and reverse explanation there are several ways to make a pin an input. when a program begins, all of the basic stamp's pins are inputs. commands that rely on input pins, like pulsin and serin, automa tically change the specified pin to input. writing 0s to particular bi ts of the variable dirs makes the corresponding pins inputs. and then there?s the input command. when a pin is an input, your program can check its state by reading the corresponding ins variable (pins on the bs1). for example: input 4 hold: if in4 = 0 then hold ' stay here until p4 = 1 the code above will read the state of p4 as set by external circuitry. if nothing is connected to p4, it will alternate between states (1 or 0) apparently at random. what happens if your program writes to the outs bit (pins bit on the bs1) of a pin that is set up as an input? the value is stored in outs (pins on the bs1), but has no effect on the ou tside world. if the pin is changed to output, the last value written to the corresponding outs bit (or pins bit 1 a ll 2 note: expressions are not allowed as arguments on the bs1. the range of the pin argument on the bs1 is 0 ? 7. 1 all 2
input ? basic stamp command reference page 244 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com on the bs1) will appear on the pin. the demo program shows how this works. demo program (input.bs1) ' input.bs1 ' this program demonstrates how the input/output direction of a pin is ' determined by the corresponding bit of dirs. it also shows that the ' state of the pin itself (as reflected by the corresponding bit of pins) ' is determined by the outside world when the pin is an input, and by the ' corresponding bit of outs when it's an output. to set up the demo, ' connect a 10k resistor from +5v to p7 on the basic stamp. the resistor ' to +5v puts a high (1) on the pin when it's an input. the basic stamp ' can override this state by writing a low (0) to bit 7 of outs and ' changing the pin to output. ' {$stamp bs1} ' {$pbasic 1.0} main: input 7 ' make p7 an input debug "state of p7: ", #pin7, cr pin7 = 0 ' write 0 to output latch debug "after 0 written to out7: " debug #pin7, cr output 7 ' make p7 an output debug "after p7 changed to output: " debug #pin7 demo program (input.bs2) ' input.bs2 ' this program demonstrates how the input/output direction of a pin is ' determined by the corresponding bit of dirs. it also shows that the ' state of the pin itself (as reflected by the corresponding bit of ins) ' is determined by the outside world when the pin is an input, and by the ' corresponding bit of outs when it's an output. to set up the demo, ' connect a 10k resistor from +5v to p7 on the basic stamp. the resistor ' to +5v puts a high (1) on the pin when it's an input. the basic stamp ' can override this state by writing a low (0) to bit 7 of outs and ' changing the pin to output. ' {$stamp bs2} ' {$pbasic 2.5} main: input 7 ' make p7 an input debug "state of p7: ", 1 all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? input basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 245 bin1 in7, cr out7 = 0 ' write 0 to output latch debug "after 0 written to out7: ", bin1 in7, cr output 7 ' make p7 an output debug "after p7 changed to output: ", bin1 in7
input ? basic stamp command reference page 246 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? ioterm basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 247 ioterm bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px ioterm port function switch control to main i/o pins or auxiliary i/o pins (on the bs2p40 only) depending on state of port .  port is a variable/constant/expression (0 ? 1) that specifies which i/o port to use. quick facts table 5.42: ioterm quick facts. bs2p, bs2pe, and bs2px values for port 0 = switch to main i/o group, 1 = switch to auxiliary i/o group. i/o pin ids 0 ? 15 (after ioterm command, all references affect physical pins 5 ? 20 or 21 ? 36 depending on state of port ). special notes both the bs2p and bs2pe 24-pin modules accept this command, however, only the bs2p40 gives access to the auxiliary i/o pins. related commands auxio and mainio explanation the bs2p, bs2pe and bs2px are available as 24-pin modules that are pin compatible with the bs2, bs2e and bs2sx. also available is a 40-pin module called the bs2p40, with an additional 16 i/o pins (for a total of 32). the bs2p40's i/o pins are organized into two groups, called main and auxiliary. the i/o pins in each group can be accessed in the same manner (by referencing i/o pins 0 ? 15) but access is only possible within one group at a time. the ioterm command causes the basic stamp to affect either the main or auxiliary i/o pins in all further code until the mainio, auxio or another ioterm command is reached, or the basic stamp is reset or power-cycled. the value of port determines which group of i/o pins will be referenced. using 0 for port will switch to the main i/o group and using 1 for port will switch to the auxiliary group. the following example illustrates this: high 0 ' make p0 high ioterm 1 ' port = 1, so switch to auxiliary pins low 0 ' make x0 low the first line of the above example will set i/o pin 0 of the main i/o pins (physical pin 5) high. afterward, the ioterm command tells the basic a simple ioterm example .
ioterm ? basic stamp command reference page 248 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com stamp that all commands following it should affect the auxiliary i/o pins ( port = 1) . the following low command will set i/o pin 0 of the auxiliary i/o pins (physical pin 21) low. note that the main i/o and auxiliar y i/o pins are independent of each other; the states of the main i/o pins remain unchanged while the program affects the auxiliary i/o pins, and vice versa. other commands that affect i/o group access are auxio and mainio. demo program (aux_main_term.bsp) ' aux_main_term.bsp ' this program demonstrates the use of the auxio, mainio and ioterm ' commands to affect i/o pins in the auxiliary and main i/o groups. ' {$stamp bs2p} ' {$pbasic 2.5} #select $stamp #case bs2, bs2e, bs2sx #error "program requires bs2p40" #case bs2p, bs2pe, bs2px debug "note: this program designed for the bs2p40.", cr #endselect port var bit main: do mainio ' switch to main i/o pins toggle 0 ' toggle state of i/o pin p0 pwm 1, 100, 40 ' generate pwm on i/o pin p1 auxio ' switch to auxiliary i/o pins toggle 0 ' toggle state of i/o pin x0 pulsout 1, 1000 ' generate a pulse on i/o pin x1 pwm 2, 100, 40 ' generate pwm on i/o pin x2 ioterm port ' switch to main or aux i/os ' -- depending on port toggle 3 ' toggle state of i/o pin 3 ' -- on main and aux, alternately port = ~port ' invert port pause 1000 ' 1 second delay loop end m ain i/o and auxiliary i/o pins are independent and unaffected by changes in the opposite group . 2 p note: this example program will tokenize with the 24-pin bs2p, bs2pe, and bs2px but its effects can only be seen on the bs2p40. this program uses conditional compilation techniques; see chapter 3 for more information.
5: basic stamp command reference ? lcdcmd basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 249 lcdcmd bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px lcdcmd pin, command function send a command to an lcd display.  pin is a variable/constant/expression (0 ? 1 or 8 ? 9) that specifies which i/o pins to use. the lcd requires, at most, seven i/o pins to operate. note that lcdcmd, lcdin and lcdout use a 4-bit interface to the lcd which requires a specific initialization sequence before lcdin and lcdout can be used. specifics on the initialization sequence will follow. the pin argument serves a double purpose; specifying the first pin and, indirectly, the group of other required pins. see explanation below. all i/o pins will be set to output mode.  command is a variable/constant/expression (0 ? 255) indicating the lcd command to send. quick facts table 5.43: lcdcmd quick facts. bs2p, bs2pe, and bs2px values for pin 0, 1, 8 or 9 i/o pin arrangement when pin is 0 or 1 0 or 1 (depending on pin): lcd enable (e) pin 2: lcd read/write (r/w) pin 3: lcd register select (rs) pin 4 ? 7: lcd data buss (db4 ? db7, respectively) pins i/o pin arrangement when pin is 8 or 9 8 or 9 (depending on pin): lcd enable (e) pin 10: lcd read/write (r/w) pin 11: lcd register select (rs) pin 12 ? 15: lcd data buss (db4 ? db7, respectively) pins special notes lcdcmd is designed to use the lcd's 4-bit mode only. related commands lcdin and lcdout explanation the three lcd commands (lcdcmd, lcdin and lcdout) allow the bs2p, bs2pe, and bs2px to interface dire ctly to standard lcd displays that feature a hitachi 44780 controller (part #hd44780a). this includes many 1 x 16, 2 x 16 and 4 x 20 character lcd displays. the hitachi 44780 lcd controller supports a number of special instructions for initializing the disp lay, moving the cursor, changing the default layout, etc. the lcdcmd comma nd is used to send one of these note: lcdcmd, lcdin and lcdout use a 4-bit interface to the lcd which requires a specific initialization seq uence before lcdin and lcdout can be used; read more below.
lcdcmd ? basic stamp command reference page 250 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com instructions to the lcd. it is most commonly used to initialize the display upon a power-up or reset condition. the following is an example of the lcdcmd command: lcdout 0, 24 the above code will send the scroll left command (represented by the number 24) to the lcd whose enable pin is connected to i/o pin 0. this will cause the lcd display to scroll , or shift, the entire display one character to the left. you may have noticed that the pin argument in the example above was 0. the lcdcmd command actually uses more than just this i/o pin, however. the lcdcmd command requires seven i/o pins. this is because the standard lcd displays have a parallel interface, rather than a serial one. the pin argument can be the numbers 0, 1, 8 or 9 and will result in the use of the i/o pins shown in table 5.43. figure 5.14 shows the required wiring for the above command to work. figure 5.14: example lcd circuit. shown with all connections necessary for the lcdcmd, lcdin and lcdout commands. a simple lcdcmd example . w iring the basic s tamp to an lcd.
5: basic stamp command reference ? lcdcmd basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 251 note that we could have used 1 for the pin argument and moved the lcd's enable pin (pin 6) to i/o pin 1. similarly, using 9 for the pin argument would have required us to wire the lcd's pins to i/o pins 9 through 15, rather than i/o pins 0 and 2 through 7. when the lcd is first powered-up, it defaults to an 8-bit interface and must be configured for a 4-bit buss before sending commands like the one shown above. this process is known as initializing the lcd and is the first thing your program should do upon starting up. the following code is a good example of lcd initialization. init_lcd: pause 1000 ' allow lcd to self-initialize first lcdcmd 0, %00110000 ' send wakeup sequence to lcd pause 5 ' pause required by lcd specs lcdcmd 0, %00110000 pause 0 ' pause required by lcd specs lcdcmd 0, %00110000 pause 0 ' pause required by lcd specs lcdcmd 0, %00100000 ' set data bus to 4-bit mode lcdcmd 0, %00101000 ' set to 2-line mode with 5x8 font lcdcmd 0, %00001100 ' display on without cursor lcdcmd 0, %00000110 ' auto-increment cursor this initialization code is the most co mmonly used sequence for a 2 x 16 and 4 x 20 lcd display (the 2-line mode instruction sets the 4 x 20 to 4-line mode). the pause 1000 command is op tional, but only if your program takes more than approximately 700 ms before it executes the initlcd code above. without it, upon powering yo ur circuit, the basic stamp may talk to the lcd too early, the lcd will then miss some of the commands and the display will operate st rangely, or not at all. do not change the "wake-up" and "4 -bit mode" sequence commands. however, the commands below the line that says, "set data bus to 4-bit mode" may be modified to set other desired modes. table 5.44 shows the most commonly used lcd commands. here's an example: lcdcmd 0, 16 this will make the lcd's cursor move left by one character (16 is the cursor left command), even if the cursor is not visible. the next character i nitializing the lcd; the most important ste p ! c ommon lcd commands .
lcdcmd ? basic stamp command reference page 252 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com printed on the display (with the lcdout command) will appear at the current cursor's location. here's another example: lcdcmd 0, 128 + 64 the above command will move the cursor to the first character position on the second line (on a 2 x 16 display). 128 is the move to display address command and 64 is the location number . see the "character positioning" section, below, for more information. command (in decimal) description do nothing 0 don't perform any special operation. clear display 1 clear the display and move cursor to home position. home display 2 move cursor and display to home position. inc cursor 6 set cursor direction to righ t, without a display shift. display off 8 turn off display (display data is retained). display on 12 turn on display without cursor (display is restored). blinking cursor 13 turn on display with blinking cursor. underline cursor 14 turn on display with underline cursor. cursor left 16 move cursor left one character. cursor right 20 move cursor right one character. scroll left 24 scroll display left one character. scroll right 28 scroll display right one character. move to cgram address 64 + address move pointer to character ram location. move to ddram address 128 + address move cursor to display data ram location. table 5.44: common lcd commands. these are supported by lcds with the hitachi 44780 controller. while most users will only need the commands shown in table 5.44 above, table 5.45 below details all of the instructions supported by the lcd (for advanced users). many instructions are multipurpose, depending on the state of special bits. clever mani pulation of the instruction bits will allow for po werful control of the lcd. the last command shown above (move to ddram address) is used to move the cursor to a specific posi tion on the lcd. the lcd's ddram (display data ram) is a fixed size with a unique position number for each character cell. the viewable portion of the ddram depends on the lcd's logical view position (which can be altered with the scroll display command). the default view position is called the home position; it means that the display's upper left character corresponds to ddram c haracter p ositioning : m oving the curso r . a note about advanced lcd commands .
5: basic stamp command reference ? lcdcmd basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 253 location 0. figure 5.15 indicates the position numbers for characters on the lcd screen. table 5.45: all lcd commands (for advanced users). these are supported by lcds with the hitachi 44780 controller. command code (in binary) description 7 6 5 4 3 2 1 0 clear display 0 0 0 0 0 0 0 1 clear entire display and move cursor home (address 0). home display 0 0 0 0 0 0 1 0 move cursor home and return display to home position. entry mode 0 0 0 0 0 1 m s sets cursor direction (m: 0=left, 1=right) and display scrolling (s: 0=no scroll, 1=scroll) display/cursor 0 0 0 0 1 d u b sets display on/off (d), underline cursor (u) and blinking block cursor (b). (0=off, 1=on) scroll display / shift cursor 0 0 0 1 c m 0 0 shifts display or cursor (c: 0=cursor, 1=display) left or right (m: 0=left, 1=right). function set 0 0 1 b l f 0 0 sets buss size (b: 0=4-bits, 1=8-bits), number of lines (l: 0=1-line, 1=2-lines) and font size (f: 0=5x8, 1=5x10) move to cgram address 0 1 a a a a a a move pointer to character ram location specified by address (a) move to ddram address 1 a a a a a a a move cursor to display ram location specified by address (a) note that figure 5.15 shows the most common ddram mapping, though some lcd's may have organized th e ddram differently. a little experimentation with your lcd may reveal this. figure 5.15: lcd character positions. note: many 1 x 16 displays conform to the position numbers shown on line 1 of the 2 x 16 display. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 16 80 39 103 ? ? line 1: line 2: on-screen positions* off-screen positions* 2 x 16 display 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 line 1: line 2: 4 x 20 display line 3: line 4: 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 16 17 18 19 80 81 83 36 37 38 39 100 101 102 103 *assuming the display is in the home position. 82
lcdcmd ? basic stamp command reference page 254 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com on a standard 2 x 16 character display, the following command would move the cursor to the third column of the second line: lcdcmd 0, 128 + 66 the number 128 tells the lcd we wish to move the cursor and 66 is the location number of the desired posi tion. similarly, sending just 128 (128 + 0) would move the cursor to the first character of the first line (the upper left character if the disp lay is at the home position). you may have noticed that the 2 x 16 display has many locations that are not visible; they are beyond the right edge of the screen. these locations (16 ? 39 and 80 to 103) become important for scrolling operations. for example, it is possible to move the cursor to location 16, print some text there and then issue a number of scro ll left instructions (lcdcmd 0, 24) to slowly scroll the text onto the displa y from right to left. if you did so, the ddram positions that were on the left of the screen would now be past the left edge of the screen. for example, lcdcmd 0, 24 lcdcmd 0, 24 would cause the screen to scroll to the le ft by two characters. at this point, the upper-left character in the display would actually be ddram location 2 and the lower-left character would be ddram location 66. locations 0, 1, 64 and 65 would be off the left edge of the lcd and would no longer be visible. some interesting effects can be achieved by taking advantage of this feature. the 4 x 20 lcd has a strange ddram map. the upper-right character is location 19 and the next location, 20, appears as the first character of the third line. this strange mapping is due to constraints in the lcd controller and the manufacturers de sign, and unfortunately makes the scrolling features virtually us eless on the 4 x 20 displays. even though the lcd requires many pins to talk to it, only the enable pin needs to remain dedicated to the lcd and all the other pins can be multiplexed (shared) with certain othe r devices (if wired carefully). in addition, the i/o pin connected to the lcd's r/w pin is only necessary if the lcdin command will be used in the application. if the lcdin command will not be used, lcd pin 5 (r/w pin) can be connected to s crolling the display . n otes on ddram mapping for 4 x 20 lc d s . d etails on lcd wiring .
5: basic stamp command reference ? lcdcmd basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 255 ground, the 4 resistors on lcd pins 7- 10 may be removed (connecting pins 7-10 directly to ground). note that even though this change will leave basic stamp i/o pin 2 disconnected, it will still be set to output mode for each lcdcmd and lcdout command executed. demo program (lcdinit.bsp) ' lcdinit.bsp ' this program demonstrates initialization and printing on a 2 x 16 ' character lcd display. the set of "lcd constants", below, are provided ' as pre-defined and useful lcd commands, though not all are actually ' used in this program. ' {$stamp bs2p} ' {$pbasic 2.5} #if ($stamp < bs2p) #then #error "program requires bs2p, bs2pe or bs2px." #endif lcd pin 0 lcdcls con $01 ' clear the lcd lcdhome con $02 ' move cursor home lcdcrsrl con $10 ' move cursor left lcdcrsrr con $14 ' move cursor right lcddispl con $18 ' shift chars left lcddispr con $1c ' shift chars right lcdddram con $80 ' display data ram lcdcgram con $40 ' character generator ram lcdline1 con $80 ' ddram address of line 1 lcdline2 con $c0 ' ddram address of line 2 init_lcd: pause 1000 ' allow lcd to self-initialize first lcdcmd lcd, %00110000 ' send wakeup sequence to lcd pause 5 ' pause required by lcd specs lcdcmd lcd, %00110000 pause 0 ' pause required by lcd specs lcdcmd lcd, %00110000 pause 0 ' pause required by lcd specs lcdcmd lcd, %00100000 ' set data bus to 4-bit mode lcdcmd lcd, %00101000 ' set to 2-line mode with 5x8 font lcdcmd lcd, %00001100 ' display on without cursor lcdcmd lcd, %00000110 ' auto-increment cursor main: do lcdout lcd, lcdcls, ["hello, world!"] lcdout lcd, lcdline2, ["how are you?"] note: this example program can be used with the bs2p, bs2pe, and bs2px by changing the $stamp directive accordingly.
lcdcmd ? basic stamp command reference page 256 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com pause 3000 lcdcmd lcd, lcdcls pause 500 loop end
5: basic stamp command reference ? lcdin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 257 lcdin bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px lcdin pin, command, [ inputdata ] function receive data from an lcd display.  pin is a variable/constant/expression (0 ? 1 or 8 ? 9) that specifies which i/o pins to use. the lcd requires, at most, seven i/o pins to operate. the pin argument serves a double purpose; specifying the first pin and, indirectly, the gr oup of other required pins. see explanation below. all i/o pins will be set to output mode initially and the upper i/o pins (4 ? 7 or 12 ? 15) will be set to input mode by the end of the lcdin command.  command is a variable/constant/expression (0 ? 255) indicating the lcd command to send.  inputdata is a list of variables and formatters that tells lcdin what to do with incoming data. lcdin can store data in a variable or array, interpret numeric text (decim al, binary, or hex) and store the corresponding value in a variable , wait for a fixed or variable sequence of bytes, or ignore a specified number of bytes. these actions can be combined in any order in the inputdata list. quick facts table 5.46: lcdin quick facts. bs2p, bs2pe, and bs2px values for pin 0, 1, 8 or 9 i/o pin arrangement when pin is 0 or 1 0 or 1 (depending on pin): lcd enable (e) pin 2: lcd read/write (r/w) pin 3: lcd register select (rs) pin 4 ? 7: lcd data buss (db4 ? db7, respectively) pins i/o pin arrangement when pin is 8 or 9 8 or 9 (depending on pin): lcd enable (e) pin 10: lcd read/write (r/w) pin 11: lcd register select (rs) pin 12 ? 15: lcd data buss (db4 ? db7, respectively) pins special notes lcdin is designed to use the lcd's 4-bit mode only. related commands lcdcmd and lcdout
lcdin ? basic stamp command reference page 258 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com explanation the three lcd commands (lcdcmd, lcdin and lcdout) allow the bs2p, bs2pe, and bs2px to interface dire ctly to standard lcd displays that feature a hitachi 44780 controller (part #hd44780a). this includes many 1 x 16, 2 x 16 and 4 x 20 character lcd displays. the lcdin command is used to send one instruction and then receive at least one data byte from the lcd's character generator ram or display data ram. the following is an example of the lcdin command: char var byte lcdin 0, 128, [char] the above code will read the character value at location 0 of the ddram. see the "character positioning" section, of the lcdcmd command description on page 252 for more information. the lcdin command actually uses more than just the i/o pin specified by the pin argument. the lcdin command requires seven i/o pins. this is because the standard lcd displays have a parallel interface, rather than a serial one. the pin argument can be the numbers 0, 1, 8 or 9 and will result in the use of the i/o pins shown in table 5.46. please refer to the lcdcmd command description for information on page properly wiring the lcd display. when the lcd is first powered-up, it defaults to an 8-bit interface and must be properly configured for a 4-bit buss before sending commands like the one shown above. this proc ess is known as initializing the lcd and is the first thing your program sh ould do upon starting up. please refer to the lcdcmd command description for information on properly initializing the lcd display. the lcdin command's inputdata argument is similar to the serin command's inputdata argument. this means data can be received as ascii character values, decimal, hexadecimal and binary translations and string data as in the examples belo w (assume the lcd display has "value: 3a:101" starting at the first character of the first line on the screen). a simple lcdin example . t wo very important steps : 1) w iring the b asic s tamp to an lcd. 2) initializing the lcd. r eceiving formatted data . note: lcdcmd, lcdin and lcdout use a 4-bit interface to the lcd which requires a specific initialization seq uence before lcdin and lcdout can be used; read more below.
5: basic stamp command reference ? lcdin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 259 value var byte(13) lcdin 0, 128, [value] 'receive the ascii value for "v" lcdin 0, 128, [dec value] 'receive the number 3. lcdin 0, 128, [hex value] 'receive the number $3a. lcdin 0, 128, [bin value] 'receive the number %101. lcdin 0, 128, [str value\13] 'receive the string "value: 3a:101" table 5.47 and table 5.48 list all the special formatters and conversion formatters available to the lcdin command. see the serin command for additional information and examples of their use. some possible uses of the lcdin command are 1) in combination with the lcdout command to store and read data from the unused ddram or cgram locations (as extra variable space), 2) to verify that the data from a previous lcdout command was rece ived and processed properly by the lcd, and 3) to read character data from cgram for the purposes of modifying it and storing it as a custom character. table 5.47: lcdin special formatters. special formatter action spstr l input a character string of length l bytes (up to 126) into scratch pad ram, starting at location 0. use get to retrieve the characters. str bytearray \l {\e} input a character string of length l into an array. if specified, an end character e causes the string input to end before reaching length l. remaining bytes are filled with 0s (zeros). wait ( value) wait for a sequence of bytes specified by value. value can be numbers separated by commas or quoted text (ex: 65, 66, 67 or ?abc?). the wait formatter is limited to a maximum of six characters. waitstr bytearray {\l} wait for a sequence of bytes matching a string stored in an array variable, optionally limited to l characters. if the optional l argument is left off, the end of the array-string must be marked by a byte containing a zero (0). skip length ignore length bytes of characters.
lcdin ? basic stamp command reference page 260 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com conversion formatter type of number numeric characters accepted notes dec{1..5} decimal, optionally limited to 1 ? 5 digits 0 through 9 1 sdec{1..5} signed decimal, optionally limited to 1 ? 5 digits -, 0 through 9 1,2 hex{1..4} hexadecimal, optionally lim ited to 1 ? 4 digits 0 through 9, a through f 1,3,5 shex{1..4} signed hexadecimal, optionally limited to 1 ? 4 digits -, 0 through 9, a through f 1,2,3 ihex{1..4} indicated hexadecimal, optionally limited to 1 ? 4 digits $, 0 through 9, a through f 1,3,4 ishex{1..4} signed, indicated hexadecimal, optionally limited to 1 ? 4 digits -, $, 0 through 9, a through f 1,2,3,4 bin{1..16} binary, optionally limited to 1 ? 16 digits 0, 1 1 sbin{1..16} signed binary, optionally limited to 1 ? 16 digits -, 0, 1 1,2 ibin{1..16} indicated binary, optionally limited to 1 ? 16 digits %, 0, 1 1,4 isbin{1..16} signed, indicated binary, optionally limited to 1 ? 16 digits -, %, 0, 1 1,2,4 num generic numeric input (decimal, hexadecimal or binary); hexadeci mal or binary number must be indicated $, %, 0 through 9, a through f 1, 3, 4 snum similar to num with value treated as signed with range -32768 to +32767 -, $, %, 0 through 9, a through f 1,2,3,4 table 5.48: lcdin conversion formatters 1 all numeric conversions will continue to accept new data until receiving either the specified number of digits (ex: three digits fo r dec3) or a non-numeric character. 2 to be recognized as part of a number, the minus sign (-) must immediately precede a numeric character. the minus sign character occurring in non-numeric text is ignored and any character (including a space) between a minus and a number causes the minus to be ignored. 3 the hexadecimal formatters are not case-sensi tive; ?a? through ?f? means the same as ?a? through ?f?. 4 indicated hexadecimal and binary formatters ignore all characters, even valid numerics, until they receive the appropriate prefix ($ fo r hexadecimal, % for bi nary). the indicated formatters can differentiate between text and hexadecimal (ex: abc would be interpreted by hex as a number but ihex would ignore it unless expressed as $abc). likewise, the binary version can dist inguish the decimal number 10 fr om the binary number %10. a prefix occurring in non-numeric text is i gnored, and any character (including a space) between a prefix and a number causes the prefix to be ignored. indicated, signed formatters require that the minus sign come before the prefix, as in -$1b45. 5 the hex modifier can be used for decimal to bcd conversion. see ?hex to bcd conversion? on page 97. for examples of all conversion formatters and how they process incoming data see appendix c.
5: basic stamp command reference ? lcdin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 261 demo program (lcdin.bsp) ' lcdin.bsp ' this program demonstrates initialization, printing and reading ' from a 2 x 16 character lcd display. ' {$stamp bs2p} ' {$pbasic 2.5} #if ($stamp < bs2p) #then #error "program requires bs2p, bs2pe or bs2px." #endif lcd pin 0 lcdcls con $01 ' clear the lcd lcdhome con $02 ' move cursor home lcdcrsrl con $10 ' move cursor left lcdcrsrr con $14 ' move cursor right lcddispl con $18 ' shift chars left lcddispr con $1c ' shift chars right lcdddram con $80 ' display data ram lcdcgram con $40 ' character generator ram lcdline1 con $80 ' ddram address of line 1 lcdline2 con $c0 ' ddram address of line 2 char var byte(16) init_lcd: pause 1000 ' allow lcd to self-initialize first lcdcmd lcd, %00110000 ' send wakeup sequence to lcd pause 5 ' pause required by lcd specs lcdcmd lcd, %00110000 pause 0 ' pause required by lcd specs lcdcmd lcd, %00110000 pause 0 ' pause required by lcd specs lcdcmd lcd, %00100000 ' set data bus to 4-bit mode lcdcmd lcd, %00101000 ' set to 2-line mode with 5x8 font lcdcmd lcd, %00001100 ' display on without cursor lcdcmd lcd, %00000110 ' auto-increment cursor main: do lcdout lcd, lcdcls, ["hello!"] gosub read_lcd_screen pause 3000 lcdout lcd, lcdcls, ["i'm a 2x16 lcd!"] gosub read_lcd_screen pause 3000 loop note: this example program can be used with the bs2p, bs2pe, and bs2px. this program uses conditional compilation techniques; see chapter 3 for more information.
lcdin ? basic stamp command reference page 262 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com read_lcd_screen: debug "lcd now says: " lcdin lcd, lcdline1, [str char\16] debug str char\16, cr return
5: basic stamp command reference ? lcdout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 263 lcdout bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px lcdout pin, command, [ outputdata ] function send data to an lcd display.  pin is a variable/constant/expression (0 ? 1 or 8 ? 9) that specifies which i/o pins to use. the lcd requires, at most, seven i/o pins to operate. the pin argument serves a double purpose; specifying the first pin and, indirectly, the gr oup of other required pins. see explanation below. all i/o pins will be set to output mode.  command is a variable/constant/expression (0 ? 255) indicating an lcd command to send.  outputdata is a list of variables, constants, expressions and formatters that tells lcdout how to format outgoing data. lcdout can transmit individual or repeating bytes, convert values into decimal, hex or binary text re presentations, or transmit strings of bytes from variable arrays. these actions can be combined in any order in the outputdata list. quick facts table 5.49: lcdout quick facts. bs2p, bs2pe, and bs2px values for pin 0, 1, 8 or 9 i/o pin arrangement when pin is 0 or 1 0 or 1 (depending on pin): lcd enable (e) pin 2: lcd read/write (r/w) pin 3: lcd register select (rs) pin 4 ? 7: lcd data buss (db4 ? db7, respectively) pins i/o pin arrangement when pin is 8 or 9 8 or 9 (depending on pin): lcd enable (e) pin 10: lcd read/write (r/w) pin 11: lcd register select (rs) pin 12 ? 15: lcd data buss (db4 ? db7, respectively) pins special notes lcdout is designed to use the lcd's 4-bit mode only. related commands lcdcmd and lcdin explanation the three lcd commands (lcdcmd, lcdin and lcdout) allow the bs2p, bs2pe, and bs2px to interface dire ctly to standard lcd displays that feature a hitachi 44780 controller (part #hd44780a). this includes many 1 x 16, 2 x 16 and 4 x 20 character lcd displays. note: lcdcmd, lcdin and lcdout use a 4-bit interface to the lcd which requires a specific initialization seq uence before lcdin and lcdout can be used; read more below.
lcdout ? basic stamp command reference page 264 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the lcdout command is used to send one instruction followed by at least one data byte to the lcd. the data that is output is written to the lcd's character generator ram or display data ram. the following is an example of the lcdout command: lcdout 0, 1, ["hello world!"] the above code will clear the lcd screen and then send "hello world!" to the screen. the first argument (0) is the starting i/o pin number and the second argument (1) is the lcd's instruction for clear screen. the lcdout command actually uses mo re than just the i/o pin specified by the pin argument. the lcdout command requires seven i/o pins. this is because the standard lcd displa ys have a parallel interface, rather than a serial one. the pin argument can be the numbers 0, 1, 8 or 9 and will result in the use of the i/o pins shown in table 5.49. please refer to the lcdcmd command description for information on properly wiring the lcd display. when the lcd is first powered-up, it defaults to an 8-bit interface and must be properly configured for a 4-bit buss before sending commands like the one shown above. this proc ess is known as initializing the lcd and is the first thing your program sh ould do upon starting up. please refer to the lcdcmd command description for information on properly initializing the lcd display. the lcdout command's outputdata argument is exactly like that of the debug and serout command's outputdata argument. this means data can be sent as literal text, ascii character values, repetitive values, decimal, hexadecimal and binary translations and string data as in the examples below. value var byte value = 65 lcdout 0, 0, [value] ' send "a" lcdout 0, 0, [rep value\5] ' send "aaaaa" lcdout 0, 0, [dec value] ' send "6" and "5" lcdout 0, 0, [hex value] ' send "4" and "1" lcdout 0, 0, [bin value] ' send "1000001" a simple lcdout example . t wo very important steps : 1) w iring the b asic s tamp to an lcd. 2) initializing the lcd. s ending and formatting data .
5: basic stamp command reference ? lcdout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 265 table 5.50 and table 5.51 list all the available conversion formatters and special formatters available to th e lcdout command. see the debug and serout commands for additional information and examples of their use. table 5.50: lcdout conversion formatters. conversion formatter type of number notes dec{1..5} decimal, optionally fixed to 1 ? 5 digits 1 sdec{1..5} signed decimal, optionally fixed to 1 ? 5 digits 1,2 hex{1..4} hexadecimal, optionally fixed to 1 ? 4 digits 1,3 shex{1..4} signed hexadecimal, optionally fixed to 1 ? 4 digits 1,2 ihex{1..4} indicated hexadecimal, optionally fixed to 1 ? 4 digits ($ prefix) 1 ishex{1..4} signed, indicated hexadecimal, opti onally fixed to 1 ? 4 digits ($ prefix) 1,2 bin{1..16} binary, optionally fixed to 1 ? 16 digits 1 sbin{1..16} signed binary, optionally fixed to 1 ? 16 digits 1,2 ibin{1..16} indicated binary, optionally fixed to 1 ? 16 digits (% prefix) 1 isbin{1..16} signed, indicated binary, optiona lly fixed to 1 ? 16 digits (% prefix) 1,2 1 fixed-digit formatters like dec4 will pad t he number with leading 0s if necessary; ex: dec4 65 sends 0065. if a number is larg er than the specified number of digits, the leading digits will be dropped; ex: dec4 56422 sends 6422. 2 signed modifiers work under two's complement rules. 3 the hex modifier can be used for bcd to decimal conversion. see ?hex to bcd conversion? on page 97. table 5.51: lcdout special formatters. special formatter action ? displays "symbol = x' + carriage return; where x is a number. default format is decimal, but may be combined with conversion f ormatters (ex: bin ? x to display "x = binary_number"). asc ? displays "symbol = 'x'" + carriage return; where x is an ascii c haracter. str bytearray {\l} send character string from an arra y. the optional \l argument c an be used to limit the output to l characters, otherwise, c haracters will be sent up to the fi rst byte equal to 0 or the end o f ram space is reached. rep byte \l send a string consisting of byte repeated l times (ex: rep "x"\10 sends "xxxxxxxxxx"). the command argument is useful for proceeding a set of data with a special lcd instruction. for exampl e, the code below will move the cursor to location 64 (the first charac ter on the second line) and print "hi": lcdout 0, 128 + 64, ["hi"] the next example, below, will turn on the blinking block cursor and print "yo!": u sing the command argument .
lcdout ? basic stamp command reference page 266 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com lcdout 0, 13, ["yo!"] most of the time, you will want to send data without preceding it with a command. to do this, simply use 0 for the command argument, as in: lcdout 0, 0, ["hello there!"] another use for the lcdout command is to access and create custom characters. the hitachi 44780 controller has a built-in character set that is similar to the ascii character set (at least for the first 128 characters). most of these characters are stored in rom and are not changeable, however, the first eight characters (a scii 0 though 7) are programmable. each of the programmable characters is five pixels wide and eight pixels tall. it takes eight bytes to describe each character; one byte per row (the left-most three bits are ignored). for example, the character at ascii location 0 is defined by the bit patterns stored in bytes 0 through 7 of character generator ram (cgram). the character at ascii location 1 is defined by the bit patterns stored in bytes 8 through 15 of cgram, and so on. to create a custom character, use so me graph paper to plot out the bit pattern (on and off pixels) in a 5 x 8 pattern, as shown in figure 5.16. then calculate the corresponding binary valu e of the bit pattern for each of the eight rows of character data. 43210 byte 0: character cell structure and data byte 1: byte 2: byte 3: byte 4: byte 5: byte 6: byte 7: ---------bits--------- xxx00000 xxx01010 xxx00000 xxx00100 xxx10001 xxx01110 xxx00000 xxx00000 binary values 00 10 00 04 17 14 00 00 decimal values figure 5.16: lcd character structure. after the data is calculated for each character (8 byte values per character), use the lcdout command with the "move to cgram address" instruction to insert the data into the character's cgram locations. for example, the code below will store the character shown in figure 5.16 into c reating custom characters .
5: basic stamp command reference ? lcdout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 267 character 0's cgram data locations. then it will place the cursor back on the display (ddram) and print the character on the screen. lcdout 0, 64+0, [00, 10, 00, 04, 17, 14, 00, 00] lcdout 0, 128+0, ["custom char: ", 0] the number 64 in the command argument is the lcd's "move to cgram address" instruction and the 0 that is a dded to it is the location of the first row of data for the character 0. the lcdout command will write the first outputdata value (00) to this location, the second outputdata value (10) to location 1, etc. if we wanted this custom character to affect character 1, instead of 0, we'd have to adjust the value of the "move to..." command, i.e.: 64+8. to affect character 2, we'd use 64+16. to try the example above, don't forg et to execute the lcd initialization code (shown in the lcdcmd description) first and never forget to move the cursor back to the screen (as with the last command, above) when you're done writing the character data to cgram. demo program (lcdout.bsp) ' lcdout.bsp ' this program demonstrates initialization and printing on a 2x16 ' character lcd display. ' {$stamp bs2p} ' {$pbasic 2.5} #if ($stamp < bs2p) #then #error "program requires bs2p, bs2pe or bs2px." #endif lcd pin 0 lcdcls con $01 ' clear the lcd lcdhome con $02 ' move cursor home lcdcrsrl con $10 ' move cursor left lcdcrsrr con $14 ' move cursor right lcddispl con $18 ' shift chars left lcddispr con $1c ' shift chars right lcdddram con $80 ' display data ram lcdcgram con $40 ' character generator ram lcdline1 con $80 ' ddram address of line 1 lcdline2 con $c0 ' ddram address of line 2 init_lcd: pause 1000 ' allow lcd to self-initialize first note: this example program can be used with the bs2p, bs2pe, and bs2px. this program uses conditional compilation techniques; see chapter 3 for more information.
lcdout ? basic stamp command reference page 268 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com lcdcmd lcd, %00110000 ' send wakeup sequence to lcd pause 5 ' pause required by lcd specs lcdcmd lcd, %00110000 pause 0 ' pause required by lcd specs lcdcmd lcd, %00110000 pause 0 ' pause required by lcd specs lcdcmd lcd, %00100000 ' set data bus to 4-bit mode lcdcmd lcd, %00101000 ' set to 2-line mode with 5x8 font lcdcmd lcd, %00001100 ' display on without cursor lcdcmd lcd, %00000110 ' auto-increment cursor lcdout lcd, lcdcgram, ' load custom character map [$00, $0a, $0a, $00, $11, $0e, $06, $00] main: do lcdout lcd, lcdcls, ["hello my friend."] pause 750 lcdout lcd, lcdline2, ["how are you?"] pause 1500 lcdcmd lcd, lcdcls lcdout lcd, lcdline1 + 1, ["i'm doing just"] lcdout lcd, lcdline2 + 4, ["fine! ", 0] pause 2000 loop end
5: basic stamp command reference ? let basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 269 let bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px { let } variable = value function sets variable equal to the value of value .  value is a variable/constant/expression. (0-65535).  variable is a variable which will be set equal to value . explanation let is an optional instruction for the basic stamp 1 that can be used with variable assignment statements, such as a = 5 and b = a + 2, etc. this instruction is not required and only exists on the basic stamp 1. let was a commonly used command in early forms of basic, and was originally included in the bs1 command set to accommodate programmers from that generation. parallax recommends that all new basic stamp 1 programs use assignment statements without the let command. demo program (let.bs1) ' let.bs1 ' this example demonstrates the use of let in assignment statements, which ' is optional and not recommended. note that the lunchtime and ' dinnertime routines do essentially the same thing, but the dinnertime ' method is recommended(even though the pricing scheme is not!) ' {$pbasic 1.0} ' {$stamp bs1} symbol salad = b1 symbol bread = b2 symbol soup = b3 symbol lunch = b4 symbol dinner = b5 lunchtime: let salad = 3 let bread = 1 let soup = 4 lunch = salad + bread + soup debug "lunch = $", #lunch, "plus local tax.", cr dinnertime: salad = 4 bread = 2 soup = 5 1 1
let ? basic stamp command reference page 270 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com dinner = salad + bread + soup debug "dinner = $",# lunch, "plus local tax.", cr
5: basic stamp command reference ? lookdown basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 271 lookdown bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px lookdown target, ( value0, value1, ...valuen ) , variable lookdown target, { comparisonop } [ value0, value1, ...valuen ] , variable function compare target value to a list of values and store the index number of the first value that matches into variable . if no value in the list matches, variable is left unaffected. on all bs2 models, the optional comparisonop is used as criteria for the match; th e default criteria is "equal to."  target is a variable/constant/expression (0 ? 65535) to be compared to the values in the list.  comparisonop is an optional comparison operator (as described in table 5.53) to be used as the crit eria when comparing values. when no comparisonop is specified, equal to (=) is assumed. this argument is not available on the bs1.  values are variables/constants/expressions (0 ? 65535) to be compared to target.  variable is a variable (usually a byte) that will be set to the index (0 ? 255) of the matching value in the values list. if no matching value is found, variable is left unaffected. quick facts table 5.52: lookdown quick facts. bs1 and all bs2 models limit of value entries 256 starting index number 0 if value list contains no match? variable is left unaffected related command lookup explanation lookdown works like the index in a book. in an index, you search for a topic and get the page number. lookdown searches for a target value in a list, and stores the index number of the first match in a variable. for example: note: expressions are not allowed as arguments on the bs1. 1 all 2 1 all 2
lookdown ? basic stamp command reference page 272 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com symbol value = b0 symbol result = b1 value = 17 result = 15 lookdown value, (26, 177, 13, 1, 0, 17, 99), result debug "value matches item ", #result, "in list" -- or -- value var byte result var nib value = 17 result = 15 lookdown value, [26, 177, 13, 1, 0, 17, 99], result debug "value matches item ", dec result, " in list" debug prints, ?value matches item 5 in list? because the value (17) matches item 5 of [26, 177, 13, 1, 0, 17, 99]. note that index numbers count up from 0, not 1; that is, in this list, 26 is item 0. what happens if the value doesn?t matc h any of the items in the list? try changing ?value = 17? to ?value = 2.? since 2 is not on the list, lookdown leaves result unaffected. since result contained 15 before lookdown executed, debug prints ?value matches item 15 in list.? by strategically setting the initial value of result , as we have here, your program can be written to detect when an item was not found in the list. don?t forget that text phrases are just lists of byte values, so they too are eligible for lookdown searches, as in this example: symbol value = b0 symbol result = b1 value = "f" result = 255 lookdown value, ("the quick brown fox"), result debug "value matches item ", #result, "in list" -- or -- t he index number of the first item is 0, not 1. u sing text in the value list . 1 all 2 1
5: basic stamp command reference ? lookdown basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 273 value var byte result var nib value = "f" result = 255 lookdown value, ["the quick brown fox"], result debug "value matches item ", dec result, " in list" debug prints, ?value matches item 16 in list? because the character at index item 16 is "f" in the phrase, ?the quick brown fox?. the examples above show lookdown working with lists of constants, but it also works with variables and expressions also. note, however, that expressions are not allowed as argument on the bs1. on all bs2 models, the lookdown command can also use another criteria (other than "equal to") for it s list. all of the examples above use lookdown?s default comparison operator, =, that searches for an exact match. the entire list of comaprisonops is shown in table 5.53. the "greater than" comparison operator (>) is used in the following example: value var byte result var nib value = 17 result = 15 lookdown value, >[26, 177, 13, 1, 0, 17, 99], result debug "value greater than item ", dec result, " in list" debug prints, ?value greater than item 2 in list? because the first item the value 17 is greater than is 13 (which is item 2 in the list). value is also greater than items 3 and 4, but these are ignored, because lookdown only cares about the first item that matches the criteria. this can require a certain amount of planning in devising the order of the list. see the demo program below. lookdown comparison operators (table 5.53) use unsigned 16-bit math. they will not work correctly with signed numbers, which are represented internally as two?s complement (large 16-bit integers). for example, the two?s complement repr esentation of -99 is 65437. so although -99 is certainly less than 0, it would appear to be larger than zero lookdown can use variables and expressions in the value list . u sing lookdown' s comparison operators . w atch out for unsigned math errors when using the comparison operators . all 2 all 2
lookdown ? basic stamp command reference page 274 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com to the lookdown comparison operators. the bottom line is: don?t used signed numbers with lookdown comparisons. comparisonop symbol description = find the first value target is equal to <> find the first value target is not equal to > find the first value target is greater than < find the first value target is less than >= find the first value target is greater than or equal to <= find the first value target is less than or equal to table 5.53: lookdown comparison operators. a common application for lookdown is to use it in conjunction with the branch, on...goto, or on...gosub commands to create selective jumps based on a simple variable input: ' {$pbasic 2.5} cmd var byte do debug cls, "enter cmd (slmh): " debugin cmd lookdown cmd, ["slmh"], cmd on cmd gosub _stop, _low, _medium, _high if cmd > 3 then debug cls, "command not in list" pause 2000 end loop _stop: debug cls, "stop" return _low: debug cls, "low" return _medium: debug cls, "medium" return _high: debug cls, "high" return in this example, the program waits fo r a key. here's what happens when "m" is pressed and cmd contains ?m? (ascii 77). lookdown finds that this is item 2 of a list of one-character commands and stores 2 into cmd . on...gosub then goes to item 2 of its list, which is the program label u sing lookdown with branch , on...goto or on...gosub to jump based on values . all 2
5: basic stamp command reference ? lookdown basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 275 ?_medium? at which point debug prints ?medium? on the pc screen then returns to the main loop. this is a powerful method for interpreting user input, and a lot neater than the alternative if...then instructions. another great use of lookdown is in combination with lookup to "map" non-contiguous sets of number s together. for example, you may have an application where certain numbers are received by the basic stamp and, in response, the basic stamp needs to send a specific set of numbers. this may be easy to code if the numbers are contiguous, or follow some known algebr aic equations? but what if they don't? the table below shows some sample, non-contiguous inputs and the corresponding outputs the basic stamp needs to respond with: table 5.54: non- contiguous number example. each of these values received (inputs): needs to result in each of these values sent (outputs): 5 16 14 17 1 18 43 24 26 10 22 12 30 11 so, if we receive the number 5, we need to output 16. if we received 43, we need to output 24, and so on. these numbers are not contiguous and they don't appear to be derived from any simple algorithm. we can solve this problem with two lines of code, as follows: lookdown value, [5, 14, 1, 43, 26, 22, 30], value lookup value, [16, 17, 18, 24, 10, 12, 11], value assuming our received number is in value , the first line (lookdown) will find the value in the list and store the index of the location that matches back into value. (this step "maps" the non-contiguous numbers: 5, 14, 1, etc, to a contiguous set of numbers: 0, 1, 2, etc). the second line (lookup) takes our new value , finds the number at that location and stores it back into value . if the received value was 14, lookdown stores 1 into value and lookup looks at the value at location 1 and stores 17 in value. the number 43 gets mapped to 3, 3 gets mapped to 24, and so on. this is a quick and easy fix for a potentially messy problem! demo program (lookdown.bs1) u sing lookdown with lookup to " map " non - contiguous sets of numbers . 1
lookdown ? basic stamp command reference page 276 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com ' lookdown.bs1 ' this program uses lookdown followed by lookup to map the numbers: ' 0, 10, 50, 64, 71 and 98 to 35, 40, 58, 62, 79, and 83, ' respectively. all other numbers are mapped to 255. ' {$stamp bs1} ' {$pbasic 1.0} symbol num = w0 ' holds current number symbol result = w1 ' holds mapped result main: for num = 0 to 100 result = 255 ' default value for no match lookdown num, (0, 10, 50, 64, 71, 98), result lookup result, (35, 40, 58, 62, 79, 83), result debug "num = ", #num, "result = ", #result, cr pause 100 next end demo program (lookdown.bs2) ' lookdown.bs2 ' this program uses lookdown to determine the number of decimal ' digits in a number. since lookdown uses a zero-indexed table, the ' output will be the number of digits minus one, so this gets ' corrected in the following line. note that zero is considered a ' valid number and has one digit. ' {$stamp bs2} ' {$pbasic 2.5} anum var word ' the number to study stpsz var word ' for-next step size numdig var nib ' digits in anum setup: stpsz = 2 main: for anum = 0 to 15000 step stpsz lookdown anum, <[0, 10, 100, 1000, 10000, 65535], numdig ' right-justify output debug "anum = ", rep " "\(5-numdig), dec anum, tab, "digits = ", dec numdig, cr pause 250 lookdown anum, <[0, 10, 100, 1000, 10000, 65535], stpsz lookup stpsz, [2, 2, 5, 25, 250, 500, 1000], stpsz next end all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? lookup basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 277 lookup bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px lookup index, ( value0, value1, ...valuen ) , variable lookup index, [ value0, value1, ...valuen ] , variable function find the value at location index and store it in variable . if index exceeds the highest index value of the items in the list, variable is left unaffected.  index is a variable/constant/expression (0 ? 255) indicating the list item to retrieve.  values are variables/constants/expressions (0 ? 65535) .  variable is a variable that will be set to the value at the index location. if index exceeds the highest location number, variable is left unaffected. quick facts table 5.55: lookup quick facts. bs1 and all bs2 models limit of value entries 256 starting index number 0 if index exceeds the highest location? variable is left unaffected related command lookdown explanation lookup retrieves an item from a list based on the item?s position, index, in the list. for example: symbol index = b2 symbol result = b3 index = 3 result = 255 lookup index, (26, 177, 13, 1, 0, 17, 99), result debug "item ", #index, "is: ", #result -- or -- note: expressions are not allowed as arguments on the bs1. 1 all 2 1 1
lookup ? basic stamp command reference page 278 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com index var byte result var byte index = 3 result = 255 lookup index, [26, 177, 13, 1, 0, 17, 99], result debug "item ", dec index, " is: ", dec result in this example, debug prints ?item 3 is: 1.? note that the first location number is 0. in the list above, item 0 is 26, item 1 is 177, etc. if index is beyond the end of the list, the result variable is unchanged. in the example above, if index were greater than 6, the message would have reported the result to be 255, because that?s what result contained before lookup executed. don?t forget that text phrases are just lists of byte values, so they too are eligible for lookup searches, as in this example: symbol index = b2 symbol result = b3 index = 16 result = " " lookup index, ("the quick brown fox"), result debug @result -- or -- index var byte result var byte index = 16 result = " " lookup index, ["the quick brown fox"], result debug asc ? result debug prints, ?result = 'f' ? because th e character at index item 16 is "f" in the phrase, ?the quick brown fox?. the examples above show lookup workin g with lists of constants, but it also works with variables and expressions also. note, however, that expressions are not allowed as argument on the bs1. t he index number of the first item is 0, not 1. lookup can use variables and expressions in the value list . u sing text in the value list . all 2 all 2 1
5: basic stamp command reference ? lookup basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 279 a great use of lookup is in combination with lookdown to "map" non-contiguous sets of numbers together. for example, you may have an application where certain numbers are received by the basic stamp and, in response, the basic stamp needs to send a specific set of numbers. this may be easy to code if the numbers are contiguous, or follow some known algebraic equations? but what if they don't? the table below shows some sample, non-contiguous inputs and the corresponding outputs the basic stamp needs to respond with: table 5.56: non-contiguous number example. each of these values received (inputs): needs to result in each of these values sent (outputs): 5 16 14 17 1 18 43 24 26 10 22 12 30 11 so, if we receive the number 5, we need to output 16. if we received 43, we need to output 24, and so on. these numbers are not contiguous and they don't appear to be derived from any simple algorithm. we can solve this problem with two lines of code, as follows: lookdown value, [5, 14, 1, 43, 26, 22, 30], value lookup value, [16, 17, 18, 24, 10, 12, 11], value assuming our received number is in value , the first line (lookdown) will find the value in the list and store the index of the location that matches back into value. (this step "maps" the non-contiguous numbers: 5, 14, 1, etc, to a contiguous set of numbers: 0, 1, 2, etc). the second line (lookup) takes our new value , finds the number at that location and stores it back into value . if the received value was 14, lookdown stores 1 into value and lookup looks at the value at location 1 and stores 17 in value. the number 43 gets mapped to 3, 3 gets mapped to 24, and so on. this is a quick and easy fix for a potentially messy problem! demo program (lookup.bs1) ' lookup.bs1 ' this program uses lookup to create a debug-window animation of a spinning ' propeller. the animation consists of the four ascii characters | / - \ ' which, when printed rapidly in order at a fixed location, appear to spin. ' a little imagination helps a lot here.... u sing lookup with lookdown to " map " non - contiguous sets of numbers . 1
lookup ? basic stamp command reference page 280 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com ' {$stamp bs1} ' {$pbasic 1.0} symbol idx = b2 symbol frame = b3 spinner: lookup idx, ("|/-\"), frame ' lookup current frame character debug cls, "spinner: ", #@frame ' display idx = idx + 1 // 4 ' update frame index (0..3) goto spinner ' loop forever end demo program (lookup.bs2) ' lookup.bs2 ' this program uses lookup to create a debug-window animation of a spinning ' propeller. the animation consists of the four ascii characters | / - \ ' which, when printed rapidly in order at a fixed location, appear to spin. ' a little imagination helps a lot here.... ' {$stamp bs2} ' {$pbasic 2.5} idx var nib frame var byte spinner: do lookup idx, ["|/-\"], frame ' lookup current frame character debug home, "spinner: ", frame ' display pause 150 ' pause between frames idx = idx + 1 // 4 ' update frame index (0..3) loop ' loop forever end all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? low basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 281 low bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px low pin function make the specified pin output low.  pin is a variable/constant/expression (0 ? 15) that specifies which i/o pin to set low. this pin will be placed into output mode. quick facts table 5.57: low quick facts. bs1 and all bs2 models related commands high and toggle explanation the low command sets the specified pin to 0 (a 0 volt level) and then sets its mode to output. for example, low 6 does exactly the same thing as: out6 = 0 dir6 = 1 using the low command is faster, in this case. connect an led and a resistor as shown in figure 5.17 for the demo program below. figure 5.17: example led circuit. note: expressions are not allowed as arguments on the bs1. the range of the pin argument on the bs1 is 0 ? 7. 1 a ll 2 1 all 2
low ? basic stamp command reference page 282 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com demo program (low.bs2) ' low.bs2 ' this simple program sets i/o pin 0 high for 1/2 second and low for ' 1/2 second in an endless loop. connect an led to p0 for a simple ' blinker. ' {$stamp bs2} main: high 0 pause 500 low 0 pause 500 goto main end note: this example program can be used with the bs1 and all bs2 models by changing the $stamp directive accordingly. 1 a ll 2
5: basic stamp command reference ? mainio basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 283 mainio bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px mainio function switch from control of auxiliary i/o pi ns to main i/o pins (on the bs2p40 only). quick facts table 5.58: mainio quick facts. bs2p, bs2pe, and bs2px i/o pin ids 0 ? 15 (just like auxiliary i/o, but after mainio command, all references affect physical pins 5 ? 20). special notes the 24-pin bs2p, bs2pe, and bs2px accept this command, however, only the bs2p40 gives access to the auxiliary i/o pins. related commands auxio and ioterm explanation the bs2p, bs2pe and bs2px are available as 24-pin modules that are pin compatible with the bs2, bs2e and bs2sx. also available is a 40-pin module called the bs2p40, with an additional 16 i/o pins (for a total of 32). the bs2p40's extra, or auxiliary, i/o pins can be accessed in the same manner as the main i/o pins (by using the ids 0 to 15) but only after issuing auxio or ioterm commands. the mainio command causes the basic stamp to affect the main i/o pins (the default) instead of the auxiliary i/o pins in all further code until the auxio or ioterm command is reached, or the basic stamp is reset or power-cycled. the following example illustrates this: auxio ' switch to auxiliary pins high 0 ' make x0 high mainio ' switch to main pins low 0 ' make p0 low the first line of the above example will tell the basic stamp to affect the auxiliary i/o pins in the commands following it. line 2, sets i/o pin 0 of the auxiliary i/o pins (physical pin 21) high. afterward, the mainio command tells the basic stamp that all commands following it should affect the main i/o pins. the last command, low, will set i/o pin 0 of the main i/o pins (physical pin 5) low. a simple mainio example .
mainio ? basic stamp command reference page 284 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com note that the main i/o and auxiliar y i/o pins are independent of each other; the states of the main i/o pins remain unchanged while the program affects the auxiliary i/o pins, and vice versa. other commands that affect i/o group access are auxio and ioterm. demo program (aux_main_term.bsp) ' aux_main_term.bsp ' this program demonstrates the use of the auxio, mainio and ioterm ' commands to affect i/o pins in the auxiliary and main i/o groups. ' {$stamp bs2p} ' {$pbasic 2.5} #select $stamp #case bs2, bs2e, bs2sx #error "program requires bs2p40" #case bs2p, bs2pe, bs2px debug "note: this program designed for the bs2p40.", cr #endselect port var bit main: do mainio ' switch to main i/o pins toggle 0 ' toggle state of i/o pin p0 pwm 1, 100, 40 ' generate pwm on i/o pin p1 auxio ' switch to auxiliary i/o pins toggle 0 ' toggle state of i/o pin x0 pulsout 1, 1000 ' generate a pulse on i/o pin x1 pwm 2, 100, 40 ' generate pwm on i/o pin x2 ioterm port ' switch to main or aux i/os ' -- depending on port toggle 3 ' toggle state of i/o pin 3 ' -- on main and aux, alternately port = ~port ' invert port pause 1000 ' 1 second delay loop end m ain i/o and auxiliary i/o pins are independent and unaffected by changes in the opposite group . 2 p note: this example program will tokenize with the 24-pin bs2p, bs2pe, and bs2px, but its effects can only be seen on the bs2p40. this program uses conditional compilation techniques; see chapter 3 for more information.
5: basic stamp command reference ? nap basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 285 nap bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px nap duration function enter sleep mode for a short time. power consumption is reduced as indicated in table 5.59 assuming no loads are being driven.  duration is a variable/constant/expression (0 ? 7) that specifies the duration of the reduced-power nap. the duration is (2^ duration ) * 18 ms. table 5.60 indicates the nap length for any given duration . quick facts table 5.59: nap quick facts. note: current measurements are based on 5-volt power, no extra loads, and 75 f ambient temperature. bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px current draw during run 1 ma 3 ma 25 ma 60 ma 40 ma 15 ma 55 ma current draw during nap 25 a 50 a 200 a 500 a 350 a 36 a 450 a related commands end and sleep end, sleep, and pollwait accuracy of nap -50 to 100% ( 10% @ 75 f with stable power supply) explanation nap uses the same shutdown/startup mechanism as sleep, with one big difference. during sleep, the ba sic stamp automatically compensates for variations in the speed of the watc hdog timer oscillator that serves as its alarm clock. as a result, longer sleep intervals are accurate to approximately 1 percent. table 5.60: duration and resulting length of nap. duration length of nap 0 18 ms 1 36 ms 2 72 ms 3 144 ms 4 288 ms 5 576 ms 6 1152 ms (1.152 seconds) 7 2304 ms (2.304 seconds) nap intervals are directly controll ed by the watchdog timer without compensation. variations in temperature, supply voltage, and manufacturing tolerance of the basic stamp's interpreter chip can cause note: expressions are not allowed as arguments on the bs1. nap accuracy notes . 1 a ll 2 1
nap ? basic stamp command reference page 286 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the actual timing to vary by as much as ?50, +100 percent (i.e., a duration of 0, nap can range from 9 to 36 ms). at room temperature with a fresh battery or other stable power supply, variations in the length of a nap will be less than 10 percent. one great use for nap is in a battery-powered application where at least a small amount of time is spent doing nothing. for example, you may have a program that loops endlessly, perf orming some task, that pauses for approximately 100 ms each time through the loop. you could replace your pause 100 with nap 3, as long as the timing of the 100 ms pause was not critical. the nap 3 would effect ively pause your program for about 144 ms and, at the same time, would place the basic stamp in low-power mode, which would extend your battery life. if your application is driving loads (sourcing or sinking current through output-high or output-low pins) during a nap, current will be interrupted for about 18 ms (60 s on the bs2pe) when the basic stamp wakes up. the reason is that the watchdog-timer reset that awakens the basic stamp also causes all of the pins to switch to input mode for approximately 18 ms (60 s on the bs 2pe). when the interpreter firmware regains control of the processor, it re stores the i/o direction dictated by your program. if you plan to use end, nap, pollwait or sleep in your programs, make sure that your loads can tolerate these power outages. the simplest solution is often to connect resistors high or low (to +5v or ground) as appropriate to ensure a continuing supply of current during the reset glitch. the demo program can be used to demonstrate the effects of the nap glitch with an led and resistor as shown in figure 5.18. a great use for nap; free power savings . t ips for driving loads during nap.
5: basic stamp command reference ? nap basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 287 figure 5.18: example led circuit. demo program (nap.bs2) ' nap.bs2 ' the program below lights an led by placing a low on pin 0. this completes ' the circuit from +5v, through the led and resistor, to ground. during the ' nap interval, the led stays lit, but blinks off for a fraction of a sec. ' this blink is caused by the nap wakeup mechanism during wakeup, all pins ' briefly slip into input mode, effectively disconnecting them from loads. ' {$stamp bs2} setup: low 0 ' turn led on snooze: nap 4 ' nap for 288 ms goto snooze end 1 a ll 2 note: this example program can be used with the bs1 and all bs2 models by changing the $stamp directive accordingly.
nap ? basic stamp command reference page 288 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? on basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 289 on bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px on offset goto address1, address2, ...addressn on offset gosub address1, address2, ...addressn function goto or gosub to the address specified by offset (if in range). on is similar in operation to branch with the exception that program execution can optionally return to the line following on (if using on?gosub).  offset is a variable/constant/expression (0 - 255) that specifies the index (0 - n) of the address, in the list, to goto or gosub to.  address is a label that specifies where to go for a given offset . on will ignore any list entries beyond offset 255. quick facts table 5.61: on quick facts. all bs2 models limit of address entries 256 maximum gosubs per program 255 (each on?gosub counts as one gosub, regardless of number of address list entries) maximum nested gosubs 4 related commands branch, goto and gosub explanation the on instruction is like saying, ?based on the value of offset , goto or gosub to one of these addresses.? on is useful when you want to write something like this: if (value = 0) then goto case_0 ' "goto" jump table if (value = 1) then goto case_1 if (value = 2) then goto case_2 - or - if (value = 0) then gosub case_0 ' "gosub" jump table if (value = 1) then gosub case_1 if (value = 2) then gosub case_2 note: on requires pbasic 2.5. all 2 all 2
on ? basic stamp command reference page 290 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com you can use on to organize each of these two examples into single statements: on value goto case_0, case_1, case_2 ' "goto" jump table - or - on value gosub case_0, case_1, case_2 ' "gosub" jump table this works like the previous if...then example. if the value isn?t in range (in this case if value is greater than 2), on does nothing and the program continues with the next instruction after on. see the goto and gosub command descriptions for more information. demo program (on-goto.bs2) ' on-goto.bs2 ' this program shows how the value of idx controls the destination of the ' on...goto instruction. ' {$stamp bs2} ' {$pbasic 2.5} idx var byte main: debug "idx: ", dec idx, " " on idx goto case_0, case_1, case_2 ' if idx = 0..2 goto label debug "on..goto target error.", cr ' message if idx is out of range update: idx = idx + 1 // 4 ' force idx to be 0..3 pause 1000 goto main case_0: debug "running case_0 routine", cr goto update case_1: debug "running case_1 routine", cr goto update case_2: debug "running case_2 routine", cr goto update all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? on basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 291 demo program (on-gosub.bs2) ' on-gosub.bs2 ' this program demonstrates a simple task manager that can be used ' in a variety of applications. it is particularly useful in ' robotics and industrial applications. the advantage of this ' design is that task code modules may be called from other places ' in the program, including other tasks, and the overall program flow ' is maintained. ' {$stamp bs2} ' {$pbasic 2.5} task var nib main: do on task gosub task_0, task_1, task_2 ' run current task task = task + 1 // 3 ' update task pointer pause 1000 loop end task_0: debug "running task 0", cr return task_1: debug "running task 1", cr return task_2: debug "running task 2", cr return all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
on ? basic stamp command reference page 292 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? output basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 293 output bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px output pin function make the specified pin an output.  pin is a variable/constant/expression (0 ? 15) that specifies which i/o pin to set to output mode. quick facts table 5.62: output quick facts. bs1 and all bs2 models related commands input and reverse explanation there are several ways to make a pin an output. commands that rely on output pins, like pulsout and serout, automatically change the specified pin to output. writing 1s to particular bits of the variable dirs makes the corresponding pins outputs. and then there?s the output command. when a pin is an output, your program can change its state by writing to the corresponding bit in the outs variable (pins on the bs1). for example: output 4 out4 = 1 when your program changes a pin from input to output, whatever state happens to be in the corresponding bit of outs (pins on the bs1) sets the initial state of the pin. to simultaneously make a pin an output and set its state use the high and low commands. demo program (input_output.bs1) ' input_output.bs1 ' this program demonstrates how the input/output direction of a pin is ' determined by the corresponding bit of dirs. it also shows that the ' state of the pin itself (as reflected by the corresponding bit of pins) ' is determined by the outside world when the pin is an input, and by the ' corresponding bit of pins when it's an output. to set up the demo, ' connect a 10k resistor from +5v to p7 on the basic stamp. the resistor note: expressions are not allowed as arguments on the bs1. the range of the pin argument on the bs1 is 0 ? 7. e ffects of setting an input pin to an output . 1 1 a ll 2 1 all 2
output ? basic stamp command reference page 294 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com ' to +5v puts a high (1) on the pin when it's an input. the basic stamp ' can override this state by writing a low (0) to bit 7 of outs and ' changing the pin to output. ' {$stamp bs1} ' {$pbasic 1.0} main: input 7 ' make p7 an input debug "state of p7: ", #pin7, cr pin7 = 0 ' write 0 to output latch debug "after 0 written to out7: " debug #pin7, cr output 7 ' make p7 an output debug "after p7 changed to output: " debug #pin7 end demo program (input_output.bs2) ' input_output.bs2 ' this program demonstrates how the input/output direction of a pin is ' determined by the corresponding bit of dirs. it also shows that the ' state of the pin itself (as reflected by the corresponding bit of ins) ' is determined by the outside world when the pin is an input, and by the ' corresponding bit of outs when it's an output. to set up the demo, ' connect a 10k resistor from +5v to p7 on the basic stamp. the resistor ' to +5v puts a high (1) on the pin when it's an input. the basic stamp ' can override this state by writing a low (0) to bit 7 of outs and ' changing the pin to output. ' {$stamp bs2} ' {$pbasic 2.5} main: input 7 ' make p7 an input debug "state of p7: ", bin1 in7, cr out7 = 0 ' write 0 to output latch debug "after 0 written to out7: ", bin1 in7, cr output 7 ' make p7 an output debug "after p7 changed to output: ", bin1 in7 end all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? owin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 295 owin bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px owin pin, mode, [ inputdata ] function receive data from a device using the 1-wire protocol.  pin is a variable/constant/expression (0 ? 15) that specifies which i/o pin to use. 1-wire devices re quire only one i/o pin (called dq) to communicate. this i/o pin will be toggled between output and input mode during the owin command and will be set to input mode by the end of the owin command.  mode is a variable/constant/expression (0 ? 15) indicating the mode of data transfer. the mode argument controls placement of reset pulses (and detection of presence pulses) as well as byte vs. bit input and normal vs. high speed. see explanation below.  inputdata is a list of variables and modifiers that tells owin what to do with incoming data. owin can st ore data in a variable or array, interpret numeric text (decimal, binary, or hex) and store the corresponding value in a variable , wait for a fixed or variable sequence of bytes, or ignore a specified number of bytes. these actions can be combined in any order in the inputdata list. quick facts table 5.63: owin quick facts. bs2p, bs2pe, and bs2px receive rate approximately 20 kbits/sec (low speed, not including reset pulse) special notes the dq pin (specified by pin ) must have a 4.7 k ? pull-up resistor. the bs2pe is not capable of high-speed transfers. related commands owout explanation the 1-wire protocol is a form of asynchronous serial communication developed by dallas semiconductor. it only requires one i/o pin and that pin can be shared between multiple 1-wire devices. the owin command allows the basic stamp to receive data from a 1-wire device. the following is an example of the owin command: result var byte owin 0, 1, [result] a simple owin example .
owin ? basic stamp command reference page 296 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com this code will transmit a "reset" pulse to a 1-wire device (connected to i/o pin 0) and then will detect the device 's "presence" pulse and then receive one byte and store it in the variable result. the mode argument is used to control placement of reset pulses (and detection of presence pulses) and to designate byte vs. bit input and normal vs. high speed. figure 5.19 shows the meaning of each of the 4 bits of mode. table 5.64 shows just some of the 16 possible values and their effect. low/hi byte/bit beres 0 feres 1 2 3 front-end reset 0=no reset 1=generate reset before data back-end reset 0=no reset 1=generate reset after data low/high speed 0=low 1=high byte/bit transfer 0=byte 1=bit figure 5.19: mode format. mode effect 0 no reset, byte mode, low speed 1 reset before data, byte mode, low speed 2 reset after data, byte mode, low speed 3 reset before and after data, byte mode, low speed 4 no reset, bit mode, low speed 5 reset before data, bit mode, low speed 8 no reset, byte mode, high speed 9 reset before data, byte mode, high speed table 5.64: owin mode values. note: the bs2pe is not capable of high-speed transfers. the proper value for mode depends on the 1-wire device and the portion of the communication you?re working on. please consult the data sheet for the device in question to determine the correct value for mode . in many cases, however, when using the owin command, mode should be set for either no reset (to receive data from a transaction already started by a owout command) or a back-end reset (to terminate the session after data is received). this may vary due to device and application requirements, however. when using the bit (rather than byte) mode of data transfer, all variables in the inputdata argument will only receive one bit. for example, the following code could be used to receive two bits using this mode:
5: basic stamp command reference ? owin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 297 bitone var byte bittwo var byte owin 0, 6, [bitone, bittwo] in the code above, we chose the value ?6? for mode . this sets bit transfer and back-end reset modes. also, we could have chosen to make the bitone and bittwo variables each a byte in size, but they still would only have received one bit each in the owin command (due to the mode we chose). the owin command?s inputdata argument is similar to the serin command?s inputdata argument. this means data can be received as ascii character values, decimal, hexadecimal and binary translations and string data as in the examples below. (assume a 1-wire device is used and that it transmits the string, ?value: 3a:101? every time it receives a front- end reset pulse). value var byte(13) owin 0, 1, [value] ? receive ascii value for ?v? owin 0, 1, [dec value] ? receive the number 3 owin 0, 1, [hex value] ? receive the number $3a owin 0, 1, [bin value] ? receive the number %101 owin 0, 1, [str value\13] ? receive ?value: 3a:101? table 5.65 and table 5.66 list all the special formatters and conversion formatters available to the owin command. see the serin command for additional information and examples of their use. table 5.65: owin special formatters. special formatter action spstr l input a character string of length l bytes (up to 126) into scratch pad ram, starting at location 0. use get to retrieve the characters. str bytearray \l {\e} input a character string of length l into an array. if specified, an end character e causes the string input to end before reaching length l. remaining by tes are filled with 0s (zeros). waitstr bytearray {\l} wait for a sequence of bytes matching a string stored in an array variable, optionally limited to l characters. if the optional l argument is left off, the end of the array-string must be marked by a byte containing a zero (0). skip length ignore length bytes of characters. r eceiving formatted data .
owin ? basic stamp command reference page 298 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com \conversion formatter type of number numeric characters accepted notes dec{1..5} decimal, optionally limited to 1 ? 5 digits 0 through 9 1 sdec{1..5} signed decimal, optionally limited to 1 ? 5 digits -, 0 through 9 1,2 hex{1..4} hexadecimal, optionally lim ited to 1 ? 4 digits 0 through 9, a through f 1,3,5 shex{1..4} signed hexadecimal, optionally limited to 1 ? 4 digits -, 0 through 9, a through f 1,2,3 ihex{1..4} indicated hexadecimal, optionally limited to 1 ? 4 digits $, 0 through 9, a through f 1,3,4 ishex{1..4} signed, indicated hexadecimal, optionally limited to 1 ? 4 digits -, $, 0 through 9, a through f 1,2,3,4 bin{1..16} binary, optionally limited to 1 ? 16 digits 0, 1 1 sbin{1..16} signed binary, optionally limited to 1 ? 16 digits -, 0, 1 1,2 ibin{1..16} indicated binary, optionally limited to 1 ? 16 digits %, 0, 1 1,4 isbin{1..16} signed, indicated binary, optionally limited to 1 ? 16 digits -, %, 0, 1 1,2,4 num generic numeric input (decimal, hexadecimal or binary); hexadeci mal or binary number must be indicated $, %, 0 through 9, a through f 1, 3, 4 snum similar to num with value treated as signed with range -32768 to +32767 -, $, %, 0 through 9, a through f 1,2,3,4 table 5.66: owin conversion formatters 1 all numeric conversions will continue to accept new data until receiving either the specified number of digits (ex: three digits fo r dec3) or a non-numeric character. 2 to be recognized as part of a number, the minus sign (-) must i mmediately precede a numeric character. the minus sign character occurring in non-numeric text is ignored and any character (including a space) between a minus and a number causes the minus to be ignored. 3 the hexadecimal formatters are not case-sen sitive; ?a? through ?f? means the same as ?a? through ?f?. 4 indicated hexadecimal and binary formatters ignore all characters, even valid numerics, until they receive the appropriate prefix ($ fo r hexadecimal, % for bi nary). the indicated formatters can differentiate between text and hexadecimal (ex: abc would be interpreted by hex as a number but ihex would ignore it unless expressed as $abc). likewise, the binary version can dist inguish the decimal number 10 fr om the binary number %10. a prefix occurring in non-numeric text is i gnored, and any character (including a space) between a prefix and a number causes the prefix to be ignored. indicated, signed formatters require that the minus sign come before the prefix, as in -$1b45. 5 the hex modifier can be used for decimal to bcd conversion. see ?hex to bcd conversion? on page 97. for examples of all conversion formatters and how they process incoming data, see appendix c.
5: basic stamp command reference ? owin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 299 the 1-wire protocol has a well-defined standard for transaction sequences. every transaction sequence consists of four parts: 1) initialization, 2) rom function command, 3) memory function command, and 4) transaction/data. additionally, the rom function command and memory function command are always 8 bits wide (1 byte in size) and is sent least-significant-bit (lsb) first. the initialization part consists of a reset pulse (generated by the master) and will be followed by a presence pulse (generated by all slave devices). figure 5.20 details the reset pulse generated by the basic stamp and a typical presence pulse generated by a 1-wire slave, in response. figure 5.20: owin reset and presence pulse. basic stamp?s reset pulse apx. 564 s device?s presence pulse 60 - 240 s resting state 15 - 60 s driven by basic stamp driven by 1-wire device +5 (vdd) 0 (vss) this reset pulse is controlled by the lowest two bits of the mode argument in the owin command. it can be made to appear before the rom function command (ex: mode = 1), after the transaction/data portion (ex: mode = 2), before and after the entire transaction (ex: mode = 3) or not at all (ex: mode = 0). see the section on mode , above, for more information. following the initialization part is the rom function command. the rom function command is used to a ddress the desired 1-wire device. table 5.67 shows common rom function commands. if only a single 1-wire device is connected, the skip rom command may be used to address it. if more than one 1-wire device is attached, the basic stamp will ultimately have to address them individually using the match rom command. t he 1- wire protocol format .
owin ? basic stamp command reference page 300 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com command value (in hex) action read rom $33 reads the 64-bit id of the 1-wire device. this command can only be used if there is a single 1-wire device on the line. match rom $55 this command, followed by a 64-bit id, allows the basic stamp to address a specific 1-wire device. skip rom $cc address a 1-wire device wit hout its 64-bit id. this command can only be used if there is a single 1-wire device on the line. search rom $f0 reads the 64-bit ids of all the 1-wire devices on the line. a process of elimination is used to distinguish each unique device. table 5.67: 1-wire rom function commands. the third part, the memory function command, allows the basic stamp to address specific memory locations, or features, of the 1-wire device. refer to the 1-wire device's data sheet for a list of the available memory function commands. basic stamp?s read ?0? slot apx. 72 s recovery period apx 8 s +5 (vdd) 0 (vss) basic stamp?s read ?1? slot apx. 72 s driven by basic stamp time when basic stamp samples line (apx 1 - 10 s) apx 4 s apx 4 s driven by 1-wire device or pulled-up by 5 k resister ? figure 5.21: example read slot. finally, the transaction/data section is used to read or write data to the 1-wire device. the owin command will read data at this point in the transaction. a read is accomplished by generating a brief low-pulse and sampling the line within 15 s of the falling edge of the pulse. this is called a "read slot." figure 5.21 shows typical read slots performed by the basic stamp. see the owout command for information on write slots.
5: basic stamp command reference ? owin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 301 the demo program uses a dallas semiconductor ds1820 digital thermometer device connected as follows. note that the 4.7 k ? pull-up resistor is required for proper operation. figure 5.22: ds1820 circuit. note: the 4.7 k ? resistor is required for proper operation. demo program (owin_owout.bsp) ' owin_owout.bsp ' this program demonstrates interfacing to a dallas semiconductor ds1822 ' 1-wire digital thermometer chip using the bs2p's 1-wire commands. connect ' the bs2p, bs2pe, or bs2px to the ds1822 as shown in the diagram in the ' owin or owout command description. this program uses a simplified ' approach that ignores the fractional portion of the temperature. ' {$stamp bs2p} ' {$pbasic 2.5} dq pin 0 ' 1-wire buss pin rdrom con $33 ' read serial number matchrom con $55 ' match sn -- for multiple devices skiprom con $cc ' ignore sn -- use for one device cvrttmp con $44 ' start temperature conversion rdsp con $be ' read ds1822 scratch pad tempin var word ' raw temperature sign var tempin.bit11 ' 1 = negative temperature tlo var tempin.byte0 thi var tempin.byte1 tsign var bit ' saved sign bit tempc var word ' final celsius temp tempf var word ' final fahrenheit temp main: do gosub get_temperature ' read temperature from ds1822 debug home, ' display "ds1822", cr, "------", cr, note: this example program can be used with the bs2p, bs2pe and bs2px by changing the $stamp directive accordingly.
owin ? basic stamp command reference page 302 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com sdec tempc, " c ", cr, sdec tempf, " f " pause 1000 loop end get_temperature: owout dq, 1, [skiprom, cvrttmp] ' send convert temperature command do ' wait on conversion pause 25 ' small loop pad owin dq, 4, [tempin] ' check status (bit transfer) loop until (tempin) ' 1 when complete owout dq, 1, [skiprom, rdsp] ' read ds1822 scratch pad owin dq, 2, [tlo, thi] ' get raw temp data tsign = sign ' save sign bit tempc = tempin >> 4 ' round to whole degrees tempc.byte1 = $ff * tsign ' correct twos complement bits tempf = (abs tempc) * 9 / 5 ' start f conversion if (tsign) then ' finish f conversion tempf = 32 - tempf ' c was negative else tempf = tempf + 32 ' c was positive endif return
5: basic stamp command reference ? owout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 303 owout bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px owout pin, mode, [ outputdata ] function send data to a device using the 1-wire protocol.  pin is a variable/constant/expression (0 ? 15) that specifies which i/o pin to use. 1-wire devices re quire only one i/o pin (called dq) to communicate. this i/o pin will be toggled between output and input mode during the owout co mmand and will be set to input mode by the end of the owout command.  mode is a variable/constant/expression (0 ? 15) indicating the mode of data transfer. the mode argument controls placement of reset pulses (and detection of presence pulses) as well as byte vs. bit input and normal vs. high speed. see explanation below.  outputdata is a list of variables and modifiers that tells owout how to format outgoing data. ow out can transmit individual or repeating bytes, convert values into decimal, hexadecimal or binary text representations, or transmit strings of bytes from variable arrays. these actions can be combined in any order in the outputdata list. quick facts table 5.68: owout quick facts. bs2p, bs2pe, and bs2px transmission rate approximately 20 kbits/sec (low speed, not including reset pulse) special notes the dq pin (specified by pin ) must have a 4.7 k ? pull-up resistor. the bs2pe is not capable of high-speed transfers. related command owin explanation the 1-wire protocol is a form of asynchronous serial communication developed by dallas semiconductor. it only requires one i/o pin and that pin can be shared between multiple 1-wire devices. the owout command allows the basic stamp to send data to a 1-wire device. the following is an example of the owout command: owout 0, 1, [$4e] a simple owout example .
owout ? basic stamp command reference page 304 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com this code will transmit a "reset" pulse to a 1-wire device (connected to i/o pin 0) and then will detect the device's "presence" pulse and then transmit one byte (the value $4e) . the mode argument is used to control placement of reset pulses (and detection of presence pulses) and to designate byte vs. bit input and normal vs. high speed. figure 5.23 shows the meaning of each of the 4 bits of mode . table 5.69 shows just some of the 16 possible values and their effect. low/hi byte/bit beres 0 feres 1 2 3 front-end reset 0=no reset 1=generate reset before data back-end reset 0=no reset 1=generate reset after data low/high speed 0=low 1=high byte/bit transfer 0=byte 1=bit figure 5.23: mode format. mode effect 0 no reset, byte mode, low speed 1 reset before data, byte mode, low speed 2 reset after data, byte mode, low speed 3 reset before and after data, byte mode, low speed 4 no reset, bit mode, low speed 5 reset before data, bit mode, low speed 8 no reset, byte mode, high speed 9 reset before data, byte mode, high speed table 5.69: owout mode values. note: the bs2pe is not capable of high-speed transfers. the proper value for mode depends on the 1-wire device and the portion of the communication you're working on . please consult the data sheet for the device in question to determine the correct value for mode . in many cases, however, when using the owout command, mode should be set for a front-end reset (to initialize the transaction). this may vary due to device and application requirements, however. when using the bit (rather than byte) mode of data transfer, all variables in the outputdata argument will only transmit one bit. for example, the following code could be used to send two bits using this mode:
5: basic stamp command reference ? owout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 305 bitone var bit bittwo var bit bitone = 0 bittwo = 1 owout 0, 5, [bitone, bittwo] in the code above, we chose the value "5" for mode . this sets bit transfer and front-end reset modes. also, we could have chosen to make the bitone and bittwo variables each a byte in size, but the basic stamp would still only use the their lowest bi t (bit0) as the value to transmit in the owout command (due to the mode we chose). the owout command's outputdata argument is similar to the debug and serout command's outputdata argument. this means data can be sent as literal text, ascii character values, repetitive values, decimal, hexadecimal and binary translations and string data as in the examples below. (assume a 1-wire device is used and that it transmits the string, "value: 3a:101" every time it receives a front-end reset pulse). value var byte value = 65 owout 0, 1, [value] ' send "a" owout 0, 1, [rep value\5] ' send "aaaaa" owout 0, 1, [dec value] ' send "6" and "5" owout 0, 1, [hex value] ' send "4" and "1" owout 0, 1, [bin value] ' send "1000001" table 5.70 and table 5.71 list all the special formatters and conversion formatters available to the owout command. see the debug and serout commands for additional information and examples of their use. table 5.70: owout special formatters. special formatter action ? displays "symbol = x' + carriage return; where x is a number. default format is decimal, but may be combined with conversion formatters (ex: bin ? x to display "x = binary_number"). asc ? displays "symbol = 'x'" + carriage return; where x is an ascii character. str bytearray {\l} send character string from an arra y. the optional \l argument can be used to limit the output to l characters, otherwise, characters will be sent up to the first byte equal to 0 or the end of ram space is reached. rep byte \l send a string consisting of byte repeated l times (ex: rep "x"\10 sends "xxxxxxxxxx"). s ending and formatting data .
owout ? basic stamp command reference page 306 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com conversion formatter type of number notes dec{1..5} decimal, optionally fixed to 1 ? 5 digits 1 sdec{1..5} signed decimal, optionally fixed to 1 ? 5 digits 1,2 hex{1..4} hexadecimal, optionally fixed to 1 ? 4 digits 1,3 shex{1..4} signed hexadecimal, optionally fixed to 1 ? 4 digits 1,2 ihex{1..4} indicated hexadecimal, optionally fixed to 1 ? 4 digits ($ prefix) 1 ishex{1..4} signed, indicated hexadecimal, opti onally fixed to 1 ? 4 digits ($ prefix) 1,2 bin{1..16} binary, optionally fixed to 1 ? 16 digits 1 sbin{1..16} signed binary, optionally fixed to 1 ? 16 digits 1,2 ibin{1..16} indicated binary, optionally fixed to 1 ? 16 digits (% prefix) 1 isbin{1..16} signed, indicated binary, optionally fixed to 1 ? 16 digits (% prefix) 1,2 table 5.71: owout conversion formatters. 1 fixed-digit formatters like dec4 will pad t he number with leading 0s if necessary; ex: dec4 65 sends 0065. if a number is larg er than the specified number of digits, the leading digits will be dropped; ex: dec4 56422 sends 6422. 2 signed modifiers work under two's complement rules. 3 the hex modifier can be used for bcd to decimal conversion. see ?hex to bcd conversion? on page 97. the 1-wire protocol has a well-defined standard for transaction sequences. every transaction sequence consists of four parts: 1) initialization, 2) rom function command, 3) memory function command, and 4) transaction/data. additionally, the rom function command and memory function command are always 8 bits wide (1 byte in size) and is sent least-significant-bit (lsb) first. the initialization part consists of a reset pulse (generated by the master) and will be followed by a presence pulse (generated by all slave devices). figure 5.24 details the reset pulse generated by the basic stamp and a typical presence pulse generated by a 1-wire slave, in response.
5: basic stamp command reference ? owout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 307 figure 5.24: owout reset and presence pulse. basic stamp?s reset pulse apx. 564 s device?s presence pulse 60 - 240 s resting state 15 - 60 s driven by basic stamp driven by 1-wire device +5 (vdd) 0 (vss) this reset pulse is controlled by the lowest two bits of the mode argument in the owout command. it can be made to appear before the rom function command (ex: mode = 1), after the transaction/data portion (ex: mode = 2), before and after the entire transaction (ex: mode = 3) or not at all (ex: mode = 0). see the section on mode , above, for more information. following the initialization part is the rom function command. the rom function command is used to a ddress the desired 1-wire device. table 5.72 shows common rom function commands. if only a single 1-wire device is connected, the skip rom command may be used to address it. if more than one 1-wire device is attached, the basic stamp will ultimately have to address them individually using the match rom command. table 5.72: owout rom function commands. command value (in hex) action read rom $33 reads the 64-bit id of the 1-wire device. this command can only be used if there is a single 1-wire device on the line. match rom $55 this command, followed by a 64-bit id, allows the basic stamp to address a specific 1-wire device. skip rom $cc address a 1-wire device wit hout its 64-bit id. this command can only be used if there is a single 1-wire device on the line. search rom $f0 reads the 64-bit ids of all the 1-wire devices on the line. a process of elimination is used to distinguish each unique device. the third part, the memory function command, allows the basic stamp to address specific memory locations, or features, of the 1-wire device.
owout ? basic stamp command reference page 308 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com refer to the 1-wire device's data sheet for a list of the available memory function commands. finally, the transaction/data section is used to read or write data to the 1-wire device. the owout command will write data at this point in the transaction. a write is accomplished by generating a low-pulse of a varying width to indicate a 0 or a 1. this is called a "write slot" and must be at least 60 s wide. figure 5.25 shows typical write slots performed by the basic stamp. see the owin command for information on read slots. basic stamp?s write ?0? slot apx. 72 s recovery period apx 8 s +5 (vdd) 0 (vss) basic stamp?s write ?1? slot apx. 72 s apx 8 s driven by basic stamp time when 1-wire device samples line (apx 15 - 45 s) figure 5.25: example write slots. the demo program uses a dallas semiconductor ds1820 digital thermometer device connected as follows. note that the 4.7 k ? pull-up resistor is required for proper operation. figure 5.26: ds1820 circuit. note: the 4.7 k ? resistor is required for proper operation.
5: basic stamp command reference ? owout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 309 demo program (owin_owout.bsp) ' owin_owout.bsp ' this program demonstrates interfacing to a dallas semiconductor ds1822 ' 1-wire digital thermometer chip using the bs2p's 1-wire commands. connect ' the bs2p, bs2pe or bs2px to the ds1822 as shown in the diagram in the ' owin or owout command description. this program uses a simplified ' approach that ignores the fractional portion of the temperature. ' {$stamp bs2p} ' {$pbasic 2.5} dq pin 0 ' 1-wire buss pin rdrom con $33 ' read serial number matchrom con $55 ' match sn -- for multiple devices skiprom con $cc ' ignore sn -- use for one device cvrttmp con $44 ' start temperature conversion rdsp con $be ' read ds1822 scratch pad tempin var word ' raw temperature sign var tempin.bit11 ' 1 = negative temperature tlo var tempin.byte0 thi var tempin.byte1 tsign var bit ' saved sign bit tempc var word ' final celsius temp tempf var word ' final fahrenheit temp main: do gosub get_temperature ' read temperature from ds1822 debug home, ' display "ds1822", cr, "------", cr, sdec tempc, " c ", cr, sdec tempf, " f " pause 1000 loop end get_temperature: owout dq, 1, [skiprom, cvrttmp] ' send convert temperatrue command do ' wait on conversion pause 25 ' small loop pad owin dq, 4, [tempin] ' check status (bit transfer) loop until (tempin) ' 1 when complete owout dq, 1, [skiprom, rdsp] ' read ds1822 scratch pad owin dq, 2, [tlo, thi] ' get raw temp data tsign = sign ' save sign bit tempc = tempin >> 4 ' round to whole degrees tempc.byte1 = $ff * tsign ' correct twos complement bits note: this example program can be used with the bs2p, bs2pe, and bs2px by changing the $stamp directive accordingly.
owout ? basic stamp command reference page 310 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com tempf = (abs tempc) * 9 / 5 ' start f conversion if (tsign) then ' finish f conversion tempf = 32 - tempf ' c was negative else tempf = tempf + 32 ' c was positive endif return
5: basic stamp command reference ? pause basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 311 pause bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px pause duration function pause the program (do nothing) for the specified duration.  duration is a variable/constant/expression (0 ? 65535) that specifies the duration of the pause. the unit of time for duration is 1 millisecond. explanation pause delays the execution of the next program instruction for the specified number of milliseconds. for example: flash: low 0 pause 100 high 0 pause 100 goto flash this code causes pin 0 to go low for 100 ms, then high for 100 ms. the delays produced by pause are as accu rate as the ceramic-resonator time base (on the basic stamp modules), 1 percent. when you use pause in timing-critical applications, keep in mind the relatively low speed of the pbasic interpreter. this is the time required for the basic stamp to read and interpret an instruction stored in the eeprom. demo program (pause.bs2) ' pause.bs2 ' this program demonstrates the pause command's time delays. once a second, ' the program will put the message "paused..." on the screen. ' {$stamp bs2} main: debug "paused...", cr pause 1000 goto main note: expressions are not allowed as arguments on the bs1. 1 a ll 2 1 1 a ll 2 note: this example program can be used with the bs1 and all bs2 models by changing the $stamp directive accordingly.
pause ? basic stamp command reference page 312 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? pollin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 313 pollin bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px pollin pin, state function specify a polled-input pin and active state.  pin is a variable/constant/expression (0 ? 15) that specifies the i/o pin to use. this i/o pin will be set to input mode.  state is a variable/constant/expression (0 ? 1) that specifies whether to poll the i/o pin for a low (0) or a high (1) level. quick facts table 5.73: pollin quick facts. bs2p, bs2pe, and bs2px available actions in response to reaching the desired state 1) nothing, 2) set polled-output pins to a specified state, 3) run another program (in a specified program-slot), 4) wait (pause program ex ecution) until desired state is reached, 5) any combination of 2, 3 and 4, above. special notes ? the polled-input pins are monitor ed (polled) in-between each command within the pbasic code. ? on the bs2p40, polled-input pins can be defined on both main i/o and auxiliary i/o pins. these are all active regardless of which group the program happens to be using at the time of a polling event. useful spram locations locations 128 ? 135 hold polled interrupt status. see table 5.77 in the pollmode command section for more information. related commands pollmode, pollout, pollrun and pollwait explanation the pollin command is used to specify an input pin to monitor, or "poll", in-between instructions during the rest of the pbasic program. the basic stamp will then perf orm some activity (in-between instructions) when the specified state is detected. the activity performed depends on the pollmode, pollout and pollrun commands. the "polling" commands allow the basic stamp to respond to certain i/o pin events at a faster rate than what is normally possible through manual pbasic programming. the term "poll" comes from the fact that the basic stamp module?s interpreter peri odically checks the state of the designated polled-input pins. it "pol ls" these pins after the end of each pbasic command and before it reads the next pbasic command from the
pollin ? basic stamp command reference page 314 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com user program; giving the appearance that it is polling "in the background". this feature should not be confused with the concept of interrupts, as the basic stamp does not support true interrupts . the following is an example of the pollin command: pollin 0, 0 pollmode 2 the pollin command in the above code will cause the basic stamp to set i/o pin 0 to an input mode and get ready to poll it for a low (0) state. the basic stamp will not actually star t polling until it is set to the appropriate mode, however. the second line, pollmode, initiates the polling process (see the pollmode description for more information). from then on, as the basic stamp execut es the rest of the program, it will check for a low level (logic 0) on i/ o pin 0, in-between instructions. in the code above, no obvious action will be noticed since we didn't tell the basic stamp what to do when it detects a change on the i/o pin. one possible action the basic stamp can be instructed to take is to change the state of an output, called a polled-output. take a look at the next example: pollin 0, 0 pollout 1, 1 pollmode 2 main: debug "looping...", cr goto main in this example, in addition to an endless loop, we've added another polling command called pollout (see the pollout description for more information). our pollout command tells the basic stamp to set i/o pin 1 to an output mode and set it high (1) when it detects the desired poll state. the poll state is the low (0) level on i/o pin 0 that pollin told it to look for. if the polled-input pin is high, it will set polled-output pin 0 to low (0), instead. once the program reaches the endless loop, at main , it will continuously print "looping?" on the pc screen. in between reading the debug command and the goto command (and vice versa) it will check polled- input pin 0 and set polled-output pin 1 accordingly. in this case, when i/o pin 0 is set low, the basic stamp will set i/o pin 1 high. when i/o a simple pollin example . s etting one of the possible actions : polled - outputs
5: basic stamp command reference ? pollin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 315 pin 0 is set low, the basic stamp will set i/o pin 1 high. it will continue to perform this operation, in-between each command in the loop, endlessly. it's important to note that, in this example, only the debug and goto commands are being executed over and over again. the first three lines of code are only run once, yet their effects are "remembered" by the basic stamp throughout the rest of the program. if the polling commands were not used , the program would have to look like the one below in order to achieve the same effect. input 0 output 1 main: out1 = ~in0 debug "looping...", cr out1 = ~in0 goto main in this example, we create the inverse relationship of input pin 0 and output pin 1 manually, in-between the debug and goto lines. though the effects are the same as when using the polling commands, this program actually takes a little longer to run and consumes 7 additional bytes of program (eeprom) space. clearly, using the polling commands is more efficient. you can have as many polled-input and polled-output pins as you have available. if multiple polled-input pins are defined, any one of them can trigger changes on the polled-output pins that are also defined. for example: pollin 0, 0 pollin 1, 0 pollout 2, 1 pollout 3, 1 pollmode 2 main: debug "looping...", cr goto main this code sets i/o pins 0 and 1 to polled-input pins (looking for a low (0) state) and sets i/o pins 2 and 3 to polled-output pins (with a high-active f or comparison : achieving the same effects without the polling commands . u sing multiple polled - input and polled - output pins . t he basic s tamp " remembers " the polling configuration for the duration of the pbasic program .
pollin ? basic stamp command reference page 316 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com state). if either i/o pin 0 or 1 goes low, the basic stamp will set i/o pins 2 and 3 high. this works similar to a logical or operation. the truth table below shows all the possible states of these two polled-input pins and the corresponding states the basic stamp will set the polled-output pins to. polled-inputs polled-outputs 0 1 2 3 0 0 0 0 0 1 1 1 1 0 1 1 1 1 1 1 table 5.74: polled-inputs / polled-outputs truth table. normally, any polled-output pins refl ect the state changes continuously, as described above. the pollmode command supports another feature, however, where the polled-output pins wi ll latch the active state; they will change only once (when the poll state is reached) and stay in the new state until the pbasic program tells it to change again. see the pollmode description for more information. other possible actions in response to polled-input states are: 1) running another program (in a specified program slot), 2) waiting (pausing program execution with or without low- power mode) until the poll state is reached, or 3) any combination of the above-mentioned actions. demo program (poll.bsp) ' poll.bsp ' this program demonstrates pollin, pollout, and the use of the pollmode ' instruction. connect active-low inputs to pins 0, 1, 2, and 3. then ' connect an led to pin 7. the program will print "." to the debug ' window until one of the alarm buttons are pressed. this will cause ' the termination of the main loop. at this point the program will ' save the latched bits, clear them (and the polling process), then ' report the input(s) that triggered the alarm. ' {$stamp bs2p} ' {$pbasic 2.5} fdoor pin 0 bdoor pin 1 patio pin 2 rst pin 3 alarmled pin 7 alarms var byte ' alarm bits p olled - outputs can be " latched " also . note: this example program can be used with the bs2p, bs2pe, and bs2px by changing the $stamp directive accordingly.
5: basic stamp command reference ? pollin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 317 idx var nib ' loop control setup: pollin fdoor, 0 ' define alarm inputs pollin bdoor, 0 pollin patio, 0 pollout alarmled, 1 ' alarm indicator pollmode 10 ' activate latched polling debug cls, "alarms activated", cr main: do debug "." ' foreground activity pause 50 loop until (alarmled = 1) ' loop until led is on get 128, alarms ' get alarm bits pollmode 0 ' deactivate polling report: debug cls, ' alarms report "front door : ", cr, "back door : ", cr, "patio : ", cr for idx = 0 to 2 ' scan alarm bits debug crsrxy, 13, idx ' move cursor if (alarms.lowbit(idx)) then ' report each bit status debug "alarm", cr else debug "-", cr endif next debug cr, "press reset to clear..." do : loop until (rst = 0) ' wait until rst pressed goto setup end
pollin ? basic stamp command reference page 318 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? pollmode basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 319 pollmode bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px pollmode mode function specify a polled command mode.  mode is a variable/constant/expression (0 ? 15) that indicates the mode in which to process the polled command configuration. quick facts table 5.75: pollmode quick facts. bs2p, bs2pe, and bs2px special notes ? polled-output pins will either change st ates continuously, just once or not at all, depending on the pollmode command. ? a poll-mode of 2 or 4 is required for a pollwait command to work. ? if both polled-outputs and polled-run are active, the polled-output event will occur before the polled-run event. useful spram locations locations 128 ? 135 hold polled interrupt status. see table 5.77 for more information. related commands pollin, pollout, pollrun and pollwait explanation the pollmode command is used to specify the mode in which polling events and activities are processed. this activity will occur in-between instructions during the rest of the pbasic program. the "polling" commands allow the basic stamp to respond to certain i/o pin events at a faster rate than what is normally possible through manual pbasic programming. the term "poll" comes from the fact that the basic stamp's interpreter periodically checks the state of the designated polled-input pins. it "polls" these pins after the end of each pbasic command and before it reads the next pbasic command from the user program; giving the appearance that it is polling "in the background". this feature should not be confused with the concept of interrupts, as the basic stamp does not support true interrupts . the pollmode command sets one of 15 possible modes for the polling commands. it is used mainly before and/or after any pollin, pollout or pollrun commands to disable and enable the polling features as desired. table 5.76 shows the mode values and their effect.
pollmode ? basic stamp command reference page 320 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com mode effect 0 deactivate polling, clear polled-input and output configuration. 1 deactivate polling, save polled-input and output configuration. 2 activate polling with polled-output action (and polled-wait) only. 3 1 activate polling with polled-run action only. 4 2 activate polling with polled-outpu t/polled-wait and polled-run actions. 5 3 clear polled-input configuration. 6 3 clear polled-output configuration. 7 3 clear polled-input and output configuration. 8 ? 15 same at 0 ? 7 except polled-output states are latched. table 5.76: pollmode mode values. 1 after the polled-run action occurs, the mode switches to 1 (deactivated, saved) 2 after the polled-run action occurs, the mode switches to 2 (activated, outputs) 3 these modes do not override the previous mode. also, the output state of polled-outputs does not change as a result of these modes. the polled-run modes, 3 and 4, are unique. as soon as the polled-run action occurs, the mode switches to 1 (deactivated, saved) or 2 (activated, outputs), respectively. this is so that the basic stamp doesn't continuously go to the start of the designated program slot while the polled-inputs are in the desired poll state. without this "one shot" feature, your program would appear to lock-up as long as the polled-inputs are in the designated state. the clear configuration modes, 5, 6 and 7, are also unique. these modes do not override the previous mode. for example, if polled-inputs, polled-outputs and a polled-run configuration was set and the mode was set to 4 (activated, outputs and run) and later the program issued a pollmode 6 command, the polled-output configuration would be cleared but the mode would switch back to 4? still allowing the run action. this also means if, later still, the program issues a pollout command, this polled-output would ta ke effect immediately (since the mode is still 4). also note that these modes do not change the output state of previously defined polled-output pins. the pollmode command determines what action, if any, will occur in response to a polled-input event. this command works in conjunction with the pollin, pollout and pollrun commands. the following is an example of the pollmode command: a simple pollmode example .
5: basic stamp command reference ? pollmode basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 321 pollin 0, 0 pollout 1, 1 pollmode 2 main: debug "looping...", cr goto main in this example, the first two lines configure i/o pin 0 as a polled-input (looking for a low state) and i/o pin 1 as a polled-output (going high if i/o pin 0 goes low, and vice versa). the third line, pollmode, initiates the polling process and configures polled-outputs to be active. from then on, as the basic stamp executes the rest of the program, it will check for a low level (logic 0) on i/o pin 0, in-b etween instructions and will set i/o pin 1 accordingly. if, in the above example, the poll mode was set to 1 (which means deactivate polling but save configuration) i/o pins 0 and 1 would still be defined the same way, and i/o pin 1 would still be set to output mode, but no polling would take place du ring the rest of the program. here's another example that demonstrates mode 1 (deactivate but save configuration). pollin 0, 0 pollout 1, 1 pollmode 2 debug "polling configured.", cr main: pollmode 1 debug "no polling allowed here...", cr pause 1000 pollmode 2 poll_now: debug "polling now...", cr goto poll_now in this case, polling is configured and activated before "polling configured" is printed on the screen. once we reach the main routine, however, polling is disabled (via the pollmode 1 command) and no polling occurs during the printing of "no po lling allowed here?" or during the 1 second pause afterward. finally, polling is activated again, and since the configuration was saved (because of mode 1, before) the polling activity
pollmode ? basic stamp command reference page 322 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com acts just like it did initially for the remainder of the program. the ability to temporarily disable polling, without changing the configuration, can be a powerful feature for certain "critical" parts of a program. the following example contains two programs. the first should be downloaded into program slot 0 and th e second into program slot 1. ' pgm #1 (slot 0) ------------- pollin 0, 0 pollout 1, 1 pollrun 1 pollmode 4 main: debug "running program 1", cr goto main ' pgm #2 (slot 1) ------------- main: debug "running program 2", cr goto main in this example (containing two programs; one is slot 0 and the other in slot 1) program 1 (slot 0) will configure polled-input pin 0 to detect a low state and polled-output 1 to go high in response. program 1 also configures a polled-run activity (see the pollrun description for more information) to run the program in slot 1. the pollmode setting activates the polled-output and th e polled-run. then, program 1 continuously prints "running program 1" on the pc screen. once i/o pin 0 goes low, however, the basic stamp will set i/o pin 1 high, then execution will be switched to the program in slot 1 (program 2). program 2 will continuously print "r unning program 2" on the screen. from this point forward, i/o pin 1 will continue to be set low and high in response to changes occurring on i/o pin 0, but the polle d-run activity is disabled and the basic stamp endlessly runs the code in program 2's main routine. the highest locations of scratch pa d ram contain run-time information about polled interrupts. see table 5.77 below.
5: basic stamp command reference ? pollmode basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 323 table 5.77: special purpose scratch pad ram locations. location bs2p and bs2pe 127 bits 0-3, active program slot #. bits 4-7, program slot for read and write operations. 128 polled input trigger status of main i/o pins 0-7 (0 = not triggered, 1 = triggered). 129 polled input trigger status of main i/o pins 8-15 (0 = not triggered, 1 = triggered). 130 polled input trigger status of auxiliary i/o pins 0-7 (0 = not triggered, 1 = triggered). 131 polled input trigger status of auxiliary i/o pins 8-15 (0 = not triggered, 1 = triggered). 132 bits 0-3: polled-interrupt mode, set by pollmode 133 bits 0-2: polled-interrupt ?run? slot, set by pollrun. 134 bit 0: active i/o group; 0 = main i/o, 1 = auxiliary i/o. 135 bit 0: polled-output status (set by pollmode); 0 = disabled, 1= enabled. bit 1: polled-input status; 0 = none defined, 1 = at least one defined. bit 2: polled-run status (set by pollmode); 0 = disabled, 1 = enabled. bit 3: polled-output latch status; 0 = real-time mode, 1 = latch mode. bit 4: polled-input state; 0 = no trigger, 1 = triggered. bit 5: polled-output latch state; 0 = nothing latched, 1 = signal latched. bit 6: poll-wait state; 0 = no event, 1 = event occurred. (cleared by pollmode only). bit 7: polling status; 0 = not active, 1 = active. demo program (poll.bsp) ' poll.bsp ' this program demonstrates pollin, pollout, and the use of the pollmode ' instruction. connect active-low inputs to pins 0, 1, 2, and 3. then ' connect an led to pin 7. the program will print "." to the debug ' window until one of the alarm buttons are pressed. this will cause ' the termination of the main loop. at this point the program will ' save the latched bits, clear them (and the polling process), then ' report the input(s) that triggered the alarm. ' {$stamp bs2p} ' {$pbasic 2.5} fdoor pin 0 bdoor pin 1 patio pin 2 rst pin 3 alarmled pin 7 alarms var byte ' alarm bits idx var nib ' loop control note: this example program can be used with the bs2p, bs2pe, and bs2px by changing the $stamp directive accordingly.
pollmode ? basic stamp command reference page 324 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com setup: pollin fdoor, 0 ' define alarm inputs pollin bdoor, 0 pollin patio, 0 pollout alarmled, 1 ' alarm indicator pollmode 10 ' activate latched polling debug cls, "alarms activated", cr main: do debug "." ' foreground activity pause 50 loop until (alarmled = 1) ' loop until led is on get 128, alarms ' get alarm bits pollmode 0 ' deactivate polling report: debug cls, ' alarms report "front door : ", cr, "back door : ", cr, "patio : ", cr for idx = 0 to 2 ' scan alarm bits debug crsrxy, 13, idx ' move cursor if (alarms.lowbit(idx)) then ' report each bit status debug "alarm", cr else debug "-", cr endif next debug cr, "press reset to clear..." do : loop until (rst = 0) ' wait until rst pressed goto setup end
5: basic stamp command reference ? pollout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 325 pollout bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px pollout pin, state function specify a polled-output pin and active state.  pin is a variable/constant/expression (0 ? 15) that specifies the i/o pin to use. this i/o pin will be set to output mode.  state is a variable/constant/expression (0 ? 1) that specifies whether to set the i/o pin low (0) or high (1) when a polled-input pin changes to its poll state. quick facts table 5.78: pollout quick facts. bs2p, bs2pe, and bs2px special notes ? the pollout command will immediately change the i/o pin to an output mode and set its level opposite to that of state , regardless of the polled-input states or the polled mode. ? polled-output pins will either change st ates continuously, just once or not at all, depending on the pollmode command. ? on the bs2p40, polled-output pins can be defined on both main i/o and auxiliary i/o pins. these are all active regardless of which group the program happens to be using at the time of a polling event. ? if both polled-outputs and polled-run are active, the polled-output event will occur before the polled-run event. useful spram locations locations 128 ? 135 hold polled interrupt status. see table 5.77 in the pollmode command section for more information. related commands pollmode, pollin, pollrun and pollwait explanation the pollout command is used to specify an output pin that changes states in response to changes on any of the defined polled-input pins. this activity will occur in-between instructions during the rest of the pbasic program. the "polling" commands allow the basic stamp to respond to certain i/o pin events at a faster rate than what is normally possible through manual pbasic programming. the term "poll" comes from the fact that the basic stamp's interpreter periodically checks the state of the designated polled-input pins. it "polls" these pins after the end of each pbasic command and before it reads the next pbasic command from the user program; giving the appearance that it is polling "in the background".
pollout ? basic stamp command reference page 326 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com this feature should not be confused with the concept of interrupts, as the basic stamp does not support true interrupts . the pollout command achieves one of three possible actions in response to a polled-input event. this command works in conjunction with the pollin and pollmode commands. the following is an example of the pollout command: pollin 0, 0 pollout 1, 1 pollmode 2 main: debug "looping...", cr goto main in this example, the pollout command tells the basic stamp to set i/o pin 1 to an output mode and set it hi gh (1) when it detects the desired poll state. the poll state is the low (0) level on i/o pin 0 that pollin told it to look for. if the polled-input pin is high, the basic stamp will set polled-output pin 1 to low (0), instead. the basic stamp will not actually start polling until it is set to the appropriate mode, however. the third line, pollmode, initiates the polling process (see the pollmode description for more information). from then on, as the basic stamp executes the rest of the program, it w ill check for a low level (logic 0) on i/o pin 0, in-between instructions. once the program reaches the endless loop, it will continuously print "looping?" on the pc screen. in between reading the debug command and the goto command (and vice versa) it will check polled-input pin 0 and set polled-output pin 1 accordingly. in this case, when i/o pin 0 is set high, the basic stamp will set i/o pin 1 low. when i/o pin 0 is set low, the basic stamp will set i/o pin 1 high. it will continue to perform this operation, in-between each co mmand in the loop, endlessly. it's important to note that in this example only the debug and goto commands are being executed over and over again. the first three lines of code are only run once, yet their effects are "remembered" by the basic stamp throughout the rest of the program. if the polling commands were not used , the program would have to look like the one below in order to achieve the same effect. a simple pollout example . f or comparison : achieving the same effects without the polling commands . t he basic s tamp " remembers " the polling configuration for the duration of the pbasic program .
5: basic stamp command reference ? pollout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 327 input 0 output 1 main: out1 = ~in0 debug "looping...", cr out1 = ~in0 goto main in this example, we create the inverse relationship of input pin 0 and output pin 1 manually, in-between the debug and goto lines. though the effects are the same as when using the polling commands, this program actually takes a little longer to run and consumes 7 additional bytes of program (eeprom) space. clearly, using the polling commands is more efficient. you can have as many polled-input and polled-output pins as you have available. if multiple polled-output pins are defined, all of them change in response to changes on the polled-input pins. for example: pollin 0, 0 pollout 1, 0 pollout 2, 1 pollout 3, 1 pollmode 2 main: debug "looping...", cr goto main this code sets up i/o pin 0 as a polled-input pin (looking for a low (0) state) and sets i/o pins 1, 2 and 3 to polled-output pins. polled-output pin 1 is set to a low-active state and pins 2 and 3 are set to a high-active state. if i/o pin 0 goes low, the basic stamp will set i/o pin 1 low and i/o pins 2 and 3 high. the table below show s the two possible states of the polled-input pin and the corresponding states the basic stamp will set the polled-output pins to. table 5.79: pollout truth table. polled-input polled-outputs 0 1 2 3 1 1 0 0 0 0 1 1 normally, any polled-output pins refl ect the state changes continuously, as described above. the pollmode command supports another feature, u sing multiple polled - input and polled - output pins . p olled - outputs can be " latched " also .
pollout ? basic stamp command reference page 328 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com however, where the polled-output pins wi ll latch the active state; they will change only once (when the poll state is reached) and stay in the new state until the pbasic program tells it to change again. see the pollmode description for more information. a clever use of the "latched" feature is to set a polled input on the same pin as a polled output. this leaves the pin in an input state, and the ?latched? state of that input pin will be saved in the pin?s output latch bit (which is otherwise not used because the pin was la st set to input mode). this gives us the advantage of having a run-time readable bit that indicates whether the input pin changed state while we were busy. for example, suppose an application needed to respond in some way if an input pin goes high, but it doesn't need to respond immediatel y, and the other tasks should not be interrupted. in essence, we need a way to know if the pin has gone high since the last time we checked it. look at this example: alarm var out0 idx var byte setup: pollout 0, 1 pollin 0, 0 pollmode 10 work: for idx = 1 to 25 debug "working...", cr next if (alarm = 0) then work respond: debug cr, "hey, the alarm was tripped!", cr pause 1000 pollmode 10 goto work here, we set i/o pin 0 to a polled-out put, then immediately set it to a polled-input. then we set the polled-mode to latch the polled-outputs. afterwards, the program performs some work, and once in a while, checks the state of out0 (named alarm in the program). if alarm is 0, i/o pin 0 was never seen to go high. if, however, alarm is 1, i/o pin 0 must have gone high while the program was doing other work, and now it can respond in the proper manner. this even works if the input pin had gone high and then low again before we check it (as long as it was high at some point in between the instructions in our work routine). a clever trick with pollout and the "l atched " feature .
5: basic stamp command reference ? pollout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 329 it is important to note that duri ng the time between the pollout and pollin commands, i/o pin 0 will be set to an output direction. this can cause a temporary short within the circuitry connected to i/o pin 0, so it is vital that a large enough series resist or (perhaps 100 ohms or greater) be inserted on that pin to protect the external device and the basic stamp. demo program (poll.bsp) ' poll.bsp ' this program demonstrates pollin, pollout, and the use of the pollmode ' instruction. connect active-low inputs to pins 0, 1, 2, and 3. then ' connect an led to pin 7. the program will print "." to the debug ' window until one of the alarm buttons are pressed. this will cause ' the termination of the main loop. at this point the program will ' save the latched bits, clear them (and the polling process), then ' report the input(s) that triggered the alarm. ' {$stamp bs2p} ' {$pbasic 2.5} fdoor pin 0 bdoor pin 1 patio pin 2 rst pin 3 alarmled pin 7 alarms var byte ' alarm bits idx var nib ' loop control setup: pollin fdoor, 0 ' define alarm inputs pollin bdoor, 0 pollin patio, 0 pollout alarmled, 1 ' alarm indicator pollmode 10 ' activate latched polling debug cls, "alarms activated", cr main: do debug "." ' foreground activity pause 50 loop until (alarmled = 1) ' loop until led is on get 128, alarms ' get alarm bits pollmode 0 ' deactivate polling report: debug cls, ' alarms report note: this example program can be used with the bs2p, bs2pe, and bs2px by changing the $stamp directive accordingly.
pollout ? basic stamp command reference page 330 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com "front door : ", cr, "back door : ", cr, "patio : ", cr for idx = 0 to 2 ' scan alarm bits debug crsrxy, 13, idx ' move cursor if (alarms.lowbit(idx)) then ' report each bit status debug "alarm", cr else debug "-", cr endif next debug cr, "press reset to clear..." do : loop until (rst = 0) ' wait until rst pressed goto setup end
5: basic stamp command reference ? pollrun basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 331 pollrun bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px pollrun programslot function specify a program to run upon a polled-input event.  programslot is a variable/constant/expression (0 ? 7) that specifies the program slot to run when a polled-input event occurs. quick facts table 5.80: pollrun quick facts. bs2p, bs2pe, and bs2px default programslot the default polled-run slot is 0. if no pollrun command is given and a poll mode of 3 or 4 is set, the program in slot 0 will run in response to a polled-input event. special notes ? if both polled-outputs and polled-run are active, the polled-output event will occur before the polled-run event. useful spram locations locations 128 ? 135 hold polled interrupt status. see table 5.77 in the pollmode command section for more information. related commands pollmode, pollin, pollout, pollwait and run explanation the pollrun command is used to specify a program slot to run in response to a polled event. this activity can occur in between any two instructions within the rest of the pbasic program. the "polling" commands allow the basic stamp to respond to certain i/o pin events at a faster rate than what is normally possible through manual pbasic programming. the term "poll" comes from the fact that the basic stamp's interpreter periodically checks the state of the designated polled-input pins. it "polls" these pins after the end of each pbasic command and before it reads the next pbasic command from the user program; giving the appearance that it is polling "in the background". this feature should not be confused with the concept of interrupts, as the basic stamp does not support true interrupts .
pollrun ? basic stamp command reference page 332 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the following is a simple example of the pollrun command. pollin 0, 0 pollrun 1 pollmode 3 main: debug "waiting in program slot 0...", cr goto main the first line of the above code will set up i/o pin 0 as a polled-input pin looking for a low (0) state. the second line, pollrun, tells the basic stamp that when i/o pin 0 goes low, it should switch execution over to the program residing in program slot 1. the third line, pollmode, activates the polled-run configuration. once the basic stamp reaches the main routine, it will continuously print "waiting in program slot 0?" on the pc screen. in between reading the debug and goto commands, however, the basic stamp will poll i/o pin 0 and check for a high or low state. if the state of pin 0 is high, it will do nothing and continue as normal. if the state of pin 0 is low, it will switch execution over to the program in slot 1 (the second program is not shown in this example). the switch to another program slot works exactly like with the run command; the designated program is run and the basic stamp does not "return" to the previous program (similar to a goto command). note that in order for the polled-run ac tivity to occur, the poll mode must be set to either 3 or 4 (the two modes that activate polled-run). also note, that the polled-run modes, 3 and 4, are unique. as soon as the polled-run action occurs, the mode switches to 1 (deactivated, saved) or 2 (activated, outputs), respectively. this is so that the basic stamp doesn't continuously go to the start of the designated program slot while the polled-inputs are in the desired poll state. without this "one shot" feature, your program would appear to lock-up as long as the polled-inputs are in the designated state. after the program switch takes place, the programslot value is maintained. any future change to poll mode 3 or 4, without another pollrun command, will result in the previously defined program slot being used. a simple pollrun example .
5: basic stamp command reference ? pollrun basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 333 demo program (pollrun0.bsp) ' pollrun0.bsp ' this program demonstrates the pollrun command. it is intended to be ' downloaded to program slot 0, and the program called pollrun1.bsp ' should be downloaded to program slot 1. i/o pin 0 is set to watch for ' a low signal. once the main routine starts running, the program ' continuously prints it's program slot number to the screen. if i/o ' pin 0 goes low, the program in program slot 1 (which should be ' pollrun1.bsp) is run. ' {$stamp bs2p, pollrun1.bsp} ' {$pbasic 2.5} pgmslot var byte setup: pollin 0, 0 ' polled-input, look for 0 pollrun 1 ' run slot 1 on polled activation pollmode 3 ' enable polling main: get 127, pgmslot debug "running program #", dec pgmslot.lownib, cr goto main end demo program (pollrun1.bsp) ' pollrun1.bsp ' this program demonstrates the pollrun command. it is intended to be ' downloaded to program slot 1, and the program called pollrun0.bsp ' should be downloaded to program slot 0. this program is run when ' program 0 detects a low on i/o pin 0 via the polled commands. ' {$stamp bs2p} ' {$pbasic 2.5} pgmslot var byte main: get 127, pgmslot debug "running program #", dec pgmslot.lownib, cr goto main end note: this example program can be used with the bs2p, bs2pe, and bs2px by changing the $stamp directive accordingly. note: this example program can be used with the bs2p, bs2pe, and bs2px by changing the $stamp directive accordingly.
pollrun ? basic stamp command reference page 334 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? pollwait basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 335 pollwait bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px pollwait duration function pause program execution, in a low-power mode, in units of duration until any polled-input pin reaches the desired poll state.  duration is a variable/constant/expression (0 ? 8) that specifies the duration of the low-power state. the duration is (2^ duration ) * 18 ms. table 5.82 on page 336 indicates the low-power length for any given duration . using 8 as the duration is a special case; the bs2p, bs2pe, and bs2px will not go into low-power mode and will respond quicker to polled-inputs. quick facts table 5.81: pollwait quick facts. bs2p bs2pe bs2px current draw during pollwait 350 a 36 a 450 a response time with duration set to 8 less than 160 s less than 250 s less than 100 s accuracy of nap ?50 to 100% (10% @ 75 f with stable power supply) special notes ? poll mode must be 2 or 4 and at least one polled-input must be set to activate pollwait (pollwait will be ignored otherwise). ? if both polled-wait and polled-run are active, the polled-run event will occur immediately after the polled-wait detects an event. useful spram locations locations 128 ? 135 hold polled interrupt status. see table 5.77 in the pollmode command section for more information. related commands pollmode, pollin, pollout, pollrun, end, nap and sleep explanation the pollwait command is used to pause program execution and go into a low-power state until any polled-input pin reaches the desired poll state. the "polling" commands allow the basic stamp to respond to certain i/o pin events at a faster rate than what is normally possible through manual pbasic programming. the term "poll" comes from the fact that the basic stamp's interpreter periodically checks the state of the designated
pollwait ? basic stamp command reference page 336 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com polled-input pins. it "polls" these pins after the end of each pbasic command and before it reads the next pbasic command from the user program; giving the appearance that it is polling "in the background". this feature should not be confused with the concept of interrupts, as the basic stamp does not support true interrupts . the pollwait command is unique among the polling commands in that it actually causes execution to halt, until a polled-input pin event occurs. the duration argument is similar to that of the nap command; using the values 0 to 7 specifies the duration of the low-power period. after the low-power period is over, the basic stamp polls the polled-input pins and determines if any meet the desired poll state. if no polled-input is in the desired state (as set by pollin command) the basic stamp goes back into low-power mode, again, for the same duration as before. if any polled-input is in the desired state, however, the basic stamp will continue execution with the next line of code. a duration of 8 makes the basic stamp pause execution in normal running mode (not low-power mode) until a polled-input event occurs. the response time is indicated in table 5.81 on page 335. since the response time is so fast, this featur e can be used to synchronize a portion of pbasic code to an incoming pulse. duration length of low-power mode 0 18 ms 1 36 ms 2 72 ms 3 144 ms 4 288 ms 5 576 ms 6 1152 ms (1.152 seconds) 7 2304 ms (2.304 seconds) 8 no power-down table 5.82: duration values and associated low-power modes. the following is a simple example of the pollwait command. pollin 0, 0 pollmode 2 main: pollwait 2 toggle 1 goto main a simple pollwait example .
5: basic stamp command reference ? pollwait basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 337 in this example, the pollin command sets i/o pin 0 to be a polled-input pin looking for a low (0) state. the main routine immediately runs a pollwait command and specifies a duration of 2 (which results in a low-power state of 72 ms). this means that every 72 ms, the basic stamp wakes-up and checks i/o pin 0 for a low. if i/o pin 0 is high, it goes back to sleep for another 72 ms. if i/o pin 0 is low, it runs the next line of code, which toggles the state of i/o pin 1. th en the loop starts all over again. note: due to the nature of low-power mode, i/o pin 1 may toggle between high and low (at 72 ms intervals in this case) even if i/o pin 0 stays high. this is an artifact of the "reset" condition in the interpreter chip that occurs when the chip wakes up from a low-power state. upon this "reset" condition, all the i/o pins are switched to inputs for approximately 18 ms. it is the switching to inputs that will cause i/o pin 1 to appear to toggle. see the nap or sleep commands for more information. if low-power mode is not required, change the pollwait command in the example above to "pollwait 8" inst ead. this will have the effect of keeping the basic stamp in normal running mode (i.e.: no low-power glitches) and will also cause the to ggle command to execute in a much shorter amount of time after a polled-input event occurs. demo program (pollwait.bsp) ' pollwait.bsp ' this program demonstrates the pollwait command. i/o pin 0 is set to ' watch for a low signal. once the main routine starts running, the ' pollwait command causes the program to halt until the polled event ' happens (i/o pin is low) then it prints a message on the pc screen. ' it will do nothing until i/o pin is low. ' {$stamp bs2p} ' {$pbasic 2.5} setup: pollin 0, 0 ' polled-input, look for 0 pollmode 2 ' enable polling main: pollwait 8 ' wait for polled event debug "i/o pin 0 is low!", cr ' print message goto main end note: this example program can be used with the bs2p, bs2pe, and bs2px by changing the $stamp directive accordingly.
pollwait ? basic stamp command reference page 338 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? pot basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 339 pot bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px pot pin, scale, variable (see rctime) function read a 5 k ? to 50 k ? potentiometer, thermistor, photocell, or other variable resistance.  pin is a variable/constant (0 ? 7) that specifies the i/o pin to use. this pin will be set to output mode initially, then to input mode.  scale is a variable/constant (0 ? 255) used to scale the command's internal 16-bit result. see explan ation below for steps to finding the scale value to use for your circuit.  variable is a variable (usually a byte) where the final result of the reading will be stored. internally, the pot command calculates a 16-bit value, which is scaled down to an 8-bit value. explanation pot reads a variable resistance and returns a value (0 ? 255) representing the amount of time it took to discharge the capacitor through the resistance. pin must be connected to one side of the variable resistance, whose other side is connected through a capacitor to ground, as shown in figure 5.27. figure 5.27: example variable resistance circuit. p0 5 k ? to 50 k ? variable resistance vss 0.1 uf pot works by first setting the specifie d i/o pin to an output and setting its state high. this step places +5 vo lts on one side of the capacitor (see figure 5.27) and ground (0 volts) on the other side, which charges the capacitor. pot waits for 10 ms and th en sets the i/o pin to an input mode and starts its timer. initially the i/o pin will see a high (1) that will eventually drop to a low (0) when th e capacitor discharges past the 1.4- volt threshold. the timer stops once the low is seen. the value of the h ow pot really works . 1 all 2
pot ? basic stamp command reference page 340 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com variable resistor affects the time it takes to discharge the capacitor from 5 volts to approximately 1.4 volts. the 16-bit reading is multiplied by ( scale /256), so a scale value of 128 would reduce the range by approximatel y 50%, a scale of 64 would reduce to 25%, and so on. the amount by which the internal value must be scaled varies with the size of the resistor being used. finding the best scale value: 1. build the circuit shown in figure 5. 27 and plug the bs1 into the pc. 2. in the basic stamp editor select pot scaling from the run menu. a special calibration window appears, allowing you to find the best value. 3. the window asks for the number of the i/o pin to which the variable resistor is connected. select the appropriate pin (0-7) from the drop- down. 4. the editor downloads a short progra m to the bs1 (this overwrites any program already stored in the bs1). 5. the window will now show the scale factor. adjust the resistor until the smallest number is shown for scale (assuming you can adjust the resistor, as with a potentiometer). 6. once you?ve found the smallest numb er for scale, you?re done. this number should be used for the scale in the pot command. 7. optionally, you can verify the scal e number found above by selecting the pot value checkbox (so it's ch ecked). this locks the scale and causes the bs1 to read the resistor continuously. the window displays the value. if the scale is good, you should be able to adjust the resistor, achieving a 0?255 reading for the value (or as close as possible). to change the scale value and repeat this step, deselect the pot value checkbox. continue this process until you find the best scale. demo program (pot.bs1) ' pot.bs1 ' this program demonstrates the use of the pot command. connect one side ' of a 5-50k potentiometer to p0. to the other side of the potentiometer ' connect a 0.1 uf capacitor, and then connect the other side of the ' capacitor to vss (ground). before running demo program, ' use the run | pot scaling dialog to determine the best scale factor. 1
5: basic stamp command reference ? pot basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 341 ' {$stamp bs1} ' {$pbasic 1.0} symbol potpin = 0 ' pot connected to p0 symbol scale = 111 ' scale value for test circuit symbol level = b2 ' storage of pot "level" main: pot potpin, scale, level ' read pot level debug cls, "level = ", #level ' display pause 50 ' short delay goto main ' repeat forever end
pot ? basic stamp command reference page 342 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? pulsin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 343 pulsin bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px pulsin pin, state, variable function measure the width of a pulse on pin described by state and store the result in variable .  pin is a variable/constant/expression (0 ? 15) that specifies the i/o pin to use. this pin will be set to input mode.  state is a variable/constant/expression (0 ? 1) that specifies whether the pulse to be measured is low (0) or high (1). a low pulse begins with a 1-to-0 transition and a high pulse begins with a 0-to-1 transition.  variable is a variable (usually a word) in which the measured pulse duration will be stored. the unit of time for variable is described in table 5.83. quick facts table 5.83: pulsin quick facts. bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px units in variable 10 s 2 s 2 s 0.8 s 0.8 s 2 s 0.81 s maximum pulse width 655.35 ms 131.07 ms 131.07 ms 52.428 ms 52.428 ms 123.6 ms 53.08 ms related commands pulsout and count explanation pulsin is like a fast stopwatch that is triggered by a change in state (0 or 1) on the specified pin. the entire width of the specified pulse (high or low) is measured, in units shown in table 5.83, and stored in variable . many analog properties (voltage, resi stance, capacitance, frequency, duty cycle) can be measured in terms of pulse durations. this makes pulsin a valuable form of analog-to-digital conversion. pulsin will wait, for the desired pu lse, for up to the maximum pulse width it can measure, shown in table 5.83. if it sees the desired pulse, it measures the time until the end of the pulse and stores the result in variable . if it never sees the start of the pulse, or the pulse is too long note: expressions are not allowed as arguments on the bs1. the range of the pin argument on the bs1 is 0 ? 7. s pecifics of pulsin' s operation . 1 a ll 2 1
pulsin ? basic stamp command reference page 344 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com (greater than the maximum pulse wi dth shown in table 5.83) pulsin "times out" and store 0 in variable. this operation keeps your program from locking-up should the desired pulse never occur. regardless of the size of variable , pulsin internally uses a 16-bit timer. unless the pulse widths are known to be short enough to fit in an 8-bit result, it is recommended to use a wo rd-sized variable. not doing so may result in strange and misleading results as the basic stamp will only store the lower 8-bits into a byte variable. figure 5.28: r/c pulse generator. demo program (pulsin.bs1) ' pulsin.bs1 ' this program uses pulsin to measure a pulse generated by discharging a ' 0.1 uf capacitor through a 1k resistor. pressing the switch generates ' the pulse, which should ideally be approximately 120 us (12 pulsin units ' of 10 us) long. variations in component values may produce results that ' are up to 10 units off from this value. for more information on ' calculating resistor-capacitor timing, see the rctime command. ' {$stamp bs1} ' {$pbasic 1.0} symbol pulse = 7 ' pulse input pin symbol time = w1 ' pulse width (10 us units) h ow the result is reported . 1
5: basic stamp command reference ? pulsin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 345 main: pulsin pulse, 1, time ' measure positive pulse if time = 0 then main ' if 0, try again debug cls, time ' else display result goto main end demo program (pulsin.bs2) ' pulsin.bs2 ' this program uses pulsin to measure a pulse generated by discharging a ' 0.1 uf capacitor through a 1k resistor. pressing the switch generates ' the pulse, which should ideally be approximately 120 us (60 pulsin units ' of 2 us) long (for bs2 and bs2e). variations in component values may ' produce results that are up to 10 units off from this value. for more ' information on calculating resistor-capacitor timing, see the rctime ' command. ' {$stamp bs2} ' {$pbasic 2.5} pulse pin 7 ' pulse input pin #select $stamp #case bs2, bs2e, bs2pe scale con $200 ' 2.0 us per unit #case bs2sx, bs2p scale con $0cc ' 0.8 us per unit #case bs2px scale con $0cf ' 0.81 us per unit #endselect time var word main: pulsin pulse, 1, time ' measure positive pulse if (time > 0) then ' if not 0 debug home, dec time, " units ", clreol ' display raw input time = time */ scale ' adjust for stamp debug cr, dec time, " us " ' display microseconds else debug cls, "out of range" ' else error message endif pause 200 goto main end all 2 note: this example program can be used with all bs2 models. this program uses conditional compilation techniques; see chapter 3 for more information.
pulsin ? basic stamp command reference page 346 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? pulsout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 347 pulsout bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px pulsout pin, duration function generate a pulse on pin with a width of duration .  pin is a variable/constant/expression (0 ? 15) that specifies the i/o pin to use. this pin will be set to output mode.  duration is a variable/constant/expression (0 ? 65535) that specifies the duration of the pulse. the unit of time for duration is described in table 5.84. quick facts table 5.84: pulsout quick facts. bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px duration units 10 s 2 s 2 s 0.8 s 0.8 s 2 s 0.8 s maximum pulse width 655.35 ms 131.07 ms 131.07 ms 52.428 ms 52.428 ms 131.07 ms 52.428 ms related command pulsin explanation pulsout sets pin to output mode, inverts the state of that pin; waits for the specified duration ; then inverts the state of the pin again; returning the bit to its original state. the unit of duration is described in table 5.84. the following example will generate a 100 s pulse on i/o pin 7 (of the bs2): pulsout 7, 50 ' generate 100 us pulse on p7 the polarity of the pulse depends on the state of the pin before the command executes. in the example above, if pin 7 was low, pulsout would produce a positive (high) puls e. if the pin was high, pulsout would produce a negative (low) pulse. if the pin is an input, the output st ate bit, out7 (pin7 on the bs1) won?t necessarily match the state of the pin. what happens then? for example: pin 7 is an input (dir7 = 0) and pulled high by a resistor as shown in figure 5.29a. suppose that pin 7 is low when we execute the instruction: pulsout 7, 5 ' generate pulse on p7 note: expressions are not allowed as arguments on the bs1. the range of the pin argument on the bs1 is 0 ? 7. c ontrolling the polarity of the pulse . w atch out for undesirable pulse glitches . 1 a ll 2 1
pulsout ? basic stamp command reference page 348 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com figure 5.29b shows the sequence of even ts on that pin. initially, pin 7 is high. its output driver is turned off (bec ause it is in input mode), so the 10 k ? resistor sets the state on the pin. when pulsout executes, it turns on the output driver, allowing out7 (pin7 on the bs1) to control the pin. vdd 10 k ? p7 o-scope pin 7 can be connected to an oscilloscope as shown to view the results shown on the right (instruction executes) pulsout 7,5 positive pulse pin 7 in input mode (dir7 = 0, out7 = 0) but held high by resistor to vdd pin changes to output pin left as output - low (dir7 = 1, out7 = 0) a. b. figure 5.29: example pulse diagram. since out7 (pin7 on the bs1) is low, the pin goes low. after a few microseconds of preparation, pulsout inverts the state of the pin; from low to high. it leaves the pin in that state for the specified time (10s if using a bs2) and then inverts it again, leaving the pin in its original state. figure 5.30: led circuit for pulsout demo programs. demo program (pulsout.bs1) ' pulsout.bs1 ' this program blinks an led on for 25 ms at 1-second intervals. connect an ' led (active-low) to i/o pin 0. ' {$stamp bs1} ' {$pbasic 1.0} 1
5: basic stamp command reference ? pulsout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 349 setup: high 0 ' make p0 high (led off) main: pulsout 0, 2500 ' flash led for 25 ms pause 1000 ' one second delay goto main end demo program (pulsout.bs2) ' pulsout.bs2 ' this program blinks an led on for 25 ms at 1-second intervals. connect an ' led (active-low) to i/o pin 0. ' {$stamp bs2} ' {$pbasic 2.5} #select $stamp #case bs2, bs2e, bs2pe scale con 500 ' to ms for 2 us per unit #case bs2sx, bs2p, bs2px scale con 1250 ' to ms for 0.8 us per unit #endselect flash con 25 * scale ' 25 milliseconds setup: high 0 ' make p0 high (led off) main: pulsout 0, flash ' flash led pause 1000 ' one second delay goto main end note: this example program can be used with all bs2 models. this program uses conditional compilation techniques; see cha p ter 3 for more information. all 2
pulsout ? basic stamp command reference page 350 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? put basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 351 put bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px put location, { word } value { , { word } value... } function write one or more values to the sc ratch pad ram (spram ), starting at location .  location is a variable/constant/expression (0 ? 62 for bs2e and bs2sx, and 0 ? 126 for bs2p, bs2pe, and bs2px) that specifies the spram location to write to.  value is a variable/constant/expression (0 ? 255, or 0 ? 65535 if using the optional word modifier) to store in the spram. quick facts table 5.85: put quick facts. note: when the word modifier is used, the low byte of the value is written to location , the high byte to location + 1. bs2e and bs2sx bs2p, bs2pe, and bs2px scratch pad ram size and organization 64 bytes (0 ? 63). organized as bytes only. 136 bytes (0 ? 135). organized as bytes only. general purpose locations 0 - 62 0 ? 126 special use location location 63: active program slot number (read only). location 127: read/write slot and active program slot (read only). locations 128-135: polled interrupt status (read only). related commands get get and store, and spstr formatter. pbasic 2.5 syntax options multiple sequential variables may be written to the scratch pad ram. the optional word modifier may be sp ecified to store 16-bit values. explanation the put command writes value into the specified scratch pad ram (spram) location. all values in the general-purpose locations can be written to from within an y of the 8 program slots. spram is useful for passing data to programs in other program slots and for additional workspace. it is diffe rent than regular ram in that symbol names cannot be assigned directly to lo cations and each location is always configured as a byte only. the following code will write the value 100 to location 25, read it back out with get, and display it: u ses for s cratch p ad ram. note: the optional arguments require pbasic 2.5.
put ? basic stamp command reference page 352 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com temp var byte put 25, 100 ' put low byte get 25, temp ' read byte value debug dec temp ' display byte value when using the $pbasic 2. 5 directive, multiple sequential values may be stored to spram, starting at location , and the word modifier may be specified to store 16-bit values. ' {$pbasic 2.5} temp var word put 25, word 2125 ' write word value get 25, word temp ' read word value debug dec temp ' display 2125 most scratch pad ram locations are available for general use. the highest locations have a special, read-only purpose; see the get command for more information. demo program (get_put1.bsx) ' get_put1.bsx ' this example demonstrates the use of the get and put commands. first, ' slot location is read using get to display the currently running program ' number. then a set of values are written (put) into locations 0 to 9. ' afterwards, program number 1 is run. this program is a bs2sx project ' consisting of get_put1.bsx and get_put2.bsx, but will run on the bs2e, ' bs2p, bs2pe, and bs2px without modification. ' {$stamp bs2sx, get_put2.bsx} ' {$pbasic 2.5} #select $stamp #case bs2 #error "bs2e or greater required." #case bs2e, bs2sx slot con 63 #case bs2p, bs2pe, bs2px slot con 127 #endselect value var byte idx var byte setup: get slot, value s cratch p ad ram locations and their purpose . note: this is written for the bs2sx but can be used with the bs2e, bs2p, bs2pe and bs2px also. this program uses conditional compilation techniques; see chapter 3 for more information.
5: basic stamp command reference ? put basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 353 debug "program slot #", dec value.nib0, cr main: for idx = 0 to 9 value = (idx + 3) * 8 put idx, value debug " writing: ", dec2 value, " to location: ", dec2 idx, cr next debug cr run 1 end demo program (get_put2.bsx) ' get_put2.bsx ' this example demonstrates the use of the get and put commands. first, ' the slot location is read using get to display the currently running ' program number. then a set of values are read (get) from locations ' 0 to 9 and displayed on the screen for verification. this program is a ' bs2sx project consisting of get_put1.bsx and get_put2.bsx, but will run ' on the bs2e, bs2p, bs2pe, and bs2px without modification. ' {$stamp bs2sx} ' {$pbasic 2.5} #select $stamp #case bs2 #error "bs2e or greater required." #case bs2e, bs2sx slot con 63 #case bs2p, bs2pe, bs2px slot con 127 #endselect value var byte idx var byte setup: get slot, value debug "program slot #", dec value.nib0, cr main: for idx = 0 to 9 get idx, value debug " reading: ", dec2 value, " from location: ", dec2 idx, cr next end note: this is written for the bs2sx but can be used with the bs2e, bs2p, bs2pe, and bs2px also. this program uses conditional compilation techniques; see chapter 3 for more information.
put ? basic stamp command reference page 354 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? pwm basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 355 pwm bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px pwm pin, duty, cycles function convert a digital value to analog output via pulse-width modulation.  pin is a variable/constant/expression (0 ? 15) that specifies the i/o pin to use. this pin will be set to output mode initially then set to input mode when the command finishes.  duty is a variable/constant/expression (0 - 255) that specifies the analog output level (0 to 5v).  cycles is a variable/constant/expression (0 - 255) that specifies the duration of the pwm signal. quick facts table 5.86: pwm quick facts bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px units in cycles 5 ms 1 ms 1 ms 0.4 ms 0.65 ms 1.62 ms 0.4 ms average voltage equation average voltage = (duty / 255) * 5 volts required chargetime ( cycles ) equation charge time = 5 * r * c special notes pin is set to output initially, and set to input at end related commands none freqout and dtmfout explanation pulse-width modulation (pwm) allows the basic stamp (a purely digital device) to generate an analog voltage. the basic idea is this: if you make a pin output high, the voltage at that pin will be close to 5 v. output low is close to 0 v. what if you switched the pin rapidly between high and low so that it was high half the time and low half the time? the average voltage over time would be halfway between 0 and 5 v (2.5 v). pwm emits a burst of 1s and 0s whose rati o is proportional to the duty value you specify, making the average voltage over time somewhere between 0 and 5 v. the proportion of 1s to 0s in pwm is called the duty cycle. the duty cycle controls the analog voltage in a very direct way; the higher the duty cycle the higher the voltage. in the case of the basic stamp, the duty cycle can range from 0 to 255. duty is literally the proportion of 1s to 0s output by the pwm command. to determine the proportional pwm output voltage, d etermining average voltage for a particular duty cycle . note: expressions are not allowed as arguments on the bs1. the range of the pin argument on the bs1 is 0 ? 7. 1 a ll 2 1
pwm ? basic stamp command reference page 356 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com use this formula: ( duty /255) * 5v. for example, if duty is 100, (100/255) * 5v = 1.96v; pwm outputs a train of pulses whose average voltage is 1.96v. in order to convert pwm into an analog voltage we have to filter out the pulses and store the average voltage. the resistor/capacitor combination in figure 5.31 will do the job. th e capacitor will hold the voltage set by pwm even after the instruction has finished. how long it will hold the voltage depends on how much current is drawn from it by external circuitry, and the internal leakage of the capacitor. in order to hold the voltage relatively steady, a program must periodically repeat the pwm instruction to give the ca pacitor a fresh charge. figure 5.31: example pwm filter circuit. just as it takes time to discharge a capa citor, it also takes time to charge it in the first place. the pwm command lets you specify the charging time in terms of pwm cycles. the period of each cycle is shown in table 5.86. so, on the bs2, to charge a capacitor for 5ms, you would specify 5 cycles in the pwm instruction. how do you determine how long to char ge a capacitor? use this rule-of- thumb formula: charge time = 5 * r * c. for instance, figure 5.31 uses a 10 k ? (10 x 10 3 ohm) resistor and a 1 f (1 x 10 -6 f) capacitor: charge time = 5 * 10 x 10 3 * 1 x 10 -6 = 50 x 10 -3 seconds, or 50 ms. since, on the bs2, each cycle is appr oximately a millisecond, it would take at least 50 cycles to charge the ca pacitor. assuming the circuit is connected to pin 0, here?s the complete pwm instruction: pwm 0, 100, 50 ' charge to 1.96 v after outputting the pwm pulses, th e basic stamp leaves the pin in input mode (0 in the corresponding bit of dirs). in input mode, the pin?s output driver is effectively disconnected . if it were not, the steady output d etermining the appropriate cycle time for your circuit . f iltering the pwm signal .
5: basic stamp command reference ? pwm basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 357 state of the pin would change the voltage on the capacitor and undo the voltage setting established by pwm. keep in mind that leakage currents of up to 1 a can flow into or out of this ?disconnected? pin. over time, these small currents will cause the voltage on the capacitor to drift. the same applies for leakage current from an op-amp?s input, as well as the capacitor?s own internal leakage. executing pwm occasionally will reset the capacitor voltage to the intended value. pwm charges the capacitor; the load pr esented by your circuit discharges it. how long the charge lasts (and therefore how often your program should repeat the pwm command to refresh the charge) depends on how much current the circuit draws, and how stable the voltage must be. you may need to buffer pwm output with a simple op-amp follower if your load or stability requirements are more than the passive circuit of figure 5.31 can handle. the term ?pwm? applies only loosely to the action of the basic stamp's pwm command. most systems that output pwm do so by splitting a fixed period of time into an on time (1) and an off time (0). suppose the interval is 1 ms and the duty cycle is 100 / 255. conventional pwm would turn the output on for 0.39 ms and off for 0.61 ms, repeating this process each millisecond. the main advantage of this kind of pwm is its predictability; you know the exact freq uency of the pulses (in this case, 1 khz), and their widths are controlled by the duty cycle. basic stamp's pwm does not work this way. it outputs a rapid sequence of on/off pulses, as short as 1.6 s in duration, whose overall proportion over the course of a full pwm cycle of approximately a millisecond is equal to the duty cycle. this has th e advantage of very quickly zeroing in on the desired output voltage, but it does not produce the neat, orderly pulses that you might expect. all bs2 models also use this high-speed pwm to generate pseudo-sine wa ve tones with the dtmfout and freqout instructions. demo program (pwm.bs1) ' pwm.bs1 ' connect a voltmeter (such as a digital multimeter set to its voltage ' range) to the output of the circuit shown in the figure for the pwm ' command (in the manual). run the program and observe the readings on ' the meter. they should come very close to 1.96v, then decrease slightly h ow p ulse -w idth -m odulation is generated . 1
pwm ? basic stamp command reference page 358 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com ' as the capacitor discharges. try varying the interval between pwm bursts ' (by changing the pause value) and the number of pwm cycles to see their ' effect. ' {$stamp bs1} ' {$pbasic 1.0} main: pwm 0, 100, 10 ' pwm at 100/255 duty (~50 ms) pause 1000 ' wait one second goto main end demo program (pwm.bs2) ' pwm.bs2 ' connect a voltmeter (such as a digital multimeter set to its voltage ' range) to the output of the circuit shown in the figure for the pwm ' command (in the manual). run the program and observe the readings on ' the meter. they should come very close to 1.96v, then decrease slightly ' as the capacitor discharges. try varying the interval between pwm bursts ' (by changing the pause value) and the number of pwm cycles to see their ' effect. ' {$stamp bs2} ' {$pbasic 2.5} #select $stamp #case bs2, bs2e cycadj con $100 ' x 1.0, cycle adjustment (for ms) #case bs2sx cycadj con $280 ' x 2.5 #case bs2p cycadj con $187 ' x 1.53 #case bs2pe cycadj con $09e ' x 0.62 #case bs2px cycadj con $280 ' x 2.5 #endselect cycles con 50 main: pwm 0, 100, (cycles */ cycadj) ' pwm at 100/255 duty (~50 ms) pause 1000 ' wait one second goto main end all 2 note: this example program can be used with all bs2 models. this program uses conditional compilation techniques; see chapter 3 for more information.
5: basic stamp command reference ? random basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 359 random bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px random variable function generate a pseudo-random number.  variable is a variable (usually a word) whose bits will be scrambled to produce a random number. variable acts as random's input and its result output. each pass through random stores the next number, in the pseudorandom sequence, in variable . explanation random generates pseudo-random numbers ranging from 0 to 65535. they?re called ?pseudo-random? because they appear random, but are generated by a logic operation that uses the initial value in variable to "tap" into a sequence of 65535 essentially random numbers. if the same initial value, called the "seed", is always used, then the same sequence of numbers is generated. the follo wing example demonstrates this: symbol result = w1 main: result = 11000 random result debug result goto main -- or -- result var word main: result = 11000 random result debug dec ? result goto main in this example, the same number would appear on the screen over and over again. this is because the same seed value was used each time; specifically, the first line of the loop sets result to 11,000. the random command really needs a different seed value each time. moving the "result =" line out of the loop will solve this problem, as in: 1 a ll 2 1 all 2
random ? basic stamp command reference page 360 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com symbol result = w1 setup: result = 11000 main: random result debug result goto main -- or -- result var word setup: result = 11000 main: random result debug dec ? result goto main here, result is only initialized once, before the loop. each time through the loop, the previous value of result , generated by random, is used as the next seed value. this generates a more desirable set of pseudorandom numbers. in applications requiring more apparent randomness, it's necessary to "seed" random with a more random value every time. for instance, in the demo program below, random is executed continuously (using the previous resulting number as the ne xt seed value) while the program waits for the user to press a button. since the user can?t control the timing of button presses very accu rately, the results approach true randomness. figure 5.32: random button circuit. 1 all 2
5: basic stamp command reference ? random basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 361 demo program (random.bs1) ' random.bs1 ' connect a button to i/o pin 7 as shown in the figure in the random ' command description and run this program. this program uses random to ' simulate a coin toss. after 100 trials, it reports the total number of ' heads and tails thrown. ' {$stamp bs1} ' {$pbasic 1.0} symbol btn = 7 ' button input symbol flip = w0 ' a random number symbol coin = bit0 ' a bit from random number symbol trials = b2 ' number of flips symbol heads = b3 ' throws that come up heads symbol tails = b4 ' throws that come up tails symbol btnwrk = b5 ' workspace for button start: debug cls, "press the button to toss coin.", cr main: for trials = 1 to 100 ' flip coin 100 times hold: random flip ' randomize while waiting button btn, 0, 250, 100, btnwrk, 0, hold ' wait for button press branch coin, (head, tail) ' 0 = heads, 1 = tails head: debug cr, "heads!" heads = heads + 1 ' increment heads counter goto next_toss tail: debug cr, "tails..." tails = tails + 1 ' increment heads counter next_toss: next debug cr, cr, "heads: ", #heads, cr, "tails: ", #tails end demo program (random.bs2) ' random.bs2 ' connect a button to i/o pin 7 as shown in the figure in the random ' command description and run this program. this program uses random to ' simulate a coin toss. after 100 trials, it reports the total number of all 2 1 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
random ? basic stamp command reference page 362 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com ' heads and tails thrown. ' {$stamp bs2} ' {$pbasic 2.5} btn pin 7 ' button input flip var word ' a random number coin var flip.bit0 ' bit0 of the random number trials var byte ' number of flips heads var byte ' throws that come up heads tails var byte ' throws that come up tails btnwrk var byte ' workspace for button start: debug cls, "press button to start" main: for trials = 1 to 100 ' flip coin 100 times hold: random flip ' randomize while waiting button btin, 0, 250, 100, btnwrk, 0, hold ' wait for button press if (coin = 0) then ' 0 = heads, 1 = tails debug cr, "heads!" heads = heads + 1 ' increment heads counter else debug cr, "tails..." tails = tails + 1 ' increment tails counter endif next done: debug cr, cr, "heads: ", dec heads, " tails: ", dec tails end
5: basic stamp command reference ? rctime basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 363 rctime bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px (see pot) rctime pin, state, variable function measure time while pin remains in state ; usually to measure the charge/discharge time of resistor/capacitor (rc) circuit.  pin is a variable/constant/expression (0 ? 15) that specifies the i/o pin to use. this pin will be placed into input mode.  state is a variable/constant/expression (0 - 1) that specifies the desired state to measure. once pin is not in state , the command ends and stores the result in variable .  variable is a variable (usually a word) in which the time measurement will be stored. the unit of time for variable is described in table 5.87. quick facts table 5.87: rctime quick facts. bs2 bs2e bs2sx bs2p bs2pe bs2px units in variable 2 s 2 s 0.8 s 0. 75 s 2 s 0.75 s maximum pulse width 131.07 ms 131.07 ms 52.428 ms 49.151 ms 131.07 ms 49.151 ms explanation rctime can be used to measure the charge or discharge time of a resistor/capacitor circuit. this allows you to measure resistance or capacitance; use r or c sensors such as thermistors or capacitive humidity sensors or respond to user input thro ugh a potentiometer. in a broader sense, rctime can also serve as a fa st, precise stopwatch for events of very short duration. when rctime executes, it makes pin an input, then starts a counter (who's unit of time is shown in table 5.87). it stops this counter as soon as the specified pin is no longer in state (0 or 1). if pin is not in state when the instruction executes, rctime will return 1 in variable , since the instruction requires one timing cycle to discover this fact. if pin remains in state longer than 65535 timing cycles rctime returns 0. h ow rctime' s timer works . 1 all 2
rctime ? basic stamp command reference page 364 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com figure 5.33 shows suitable rc circuits for use with rctime. the circuit in figure 5.33a is preferred, because the basic stamp's logic threshold is approximately 1.4 volts. this means that the voltage seen by the pin will start at 5v then fall to 1.4v (a span of 3.6v) before rctime stops. with the circuit of figure 5.33b, the voltage will start at 0v and rise to 1.4v (spanning only 1.4v) before rctime stops. for the same combination of r and c, the circuit shown in figure 5.33a will yield a higher count, and therefore more resolution than figure 5.33b. a. b. figure 5.33: example rc circuits. use a (left) with state = 1. use b (right) with state = 0. before rctime executes, the capacitor must be put into the state specified in the rctime instruction. for exam ple, with figure 5.33a, the capacitor must be charged until the top plate is at 5v, then a state value of 1 will be used to monitor the discharge of the capacitor through the variable resistance. here?s a typical sequence of instructions for figure 5.33a (assuming i/o pin 7 is used): result var word high 7 ' charge the cap pause 1 ' for 1 ms rctime 7, 1, result ' measure rc discharge time debug dec ? result ' display result using rctime is very straightforward, except for one detail: for a given r and c, what value will rctime return ? it?s easy to figure, based on a value called the rc time constant, or tau ( ) for short. tau represents the time required for a given rc combination to charge or discharge by 63 s uitable rct ime circuits . d on ' t forget to discharge the capacitor before executing rctime. p redicting the returned value .
5: basic stamp command reference ? rctime basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 365 percent of the total change in volt age that they will undergo. more importantly, the value is used in the generalized rc timing calculation. tau?s formula is just r multiplied by c: = r x c the general rc timing formula uses to tell us the time required for an rc circuit to change from one voltage to another: time = - * ( ln (v final / v initial ) ) in this formula ln is the natural loga rithm; it?s a key on most scientific calculators. let?s do some math. assume we?re interested in a 10 k resistor and 0.1 f cap. calculate : = (10 x 10 3 ) x (0.1 x 10 -6 ) = 1 x 10 -3 the rc time constant is 1 x 10 -3 or 1 millisecond. now calculate the time required for this rc circuit to go from 5v to 1.4v (as in figure 5.33a): time = -1 x 10 -3 x (ln(1.4v / 5.0v)) = 1.273 x 10 -3 on the bs2, the unit of time is 2s (see table 5.87), that time (1.273 x 10 -3 ) works out to 636 units. with a 10 k ? resistor and 0.1 f cap, rctime would return a value of approximately 635. since v initial and v final doesn't change, we can use a simplified rule of thumb to estimate rctime results for circuits like figure 5.33a: rctime units = 635 x r (in k ? ) x c (in f) another handy rule of thumb can help you calculate how long to charge/discharge the capacitor before rctime. in the example above that?s the purpose of the high and pause commands. a given rc charges or discharges 98 percent of th e way in 5 time constants (5 x r x c). in figure 5.33, the charge/discharge current passes through the 220 ? series resistor and the capacitor. so if the capacitor were 0.1 f, the minimum charge/discharge time should be: charge time = 5 x 220 x (0.1 x 10 -6 ) = 110 x 10 -6 c alculating charge and discharge time . t he rc t ime equation . d etermining how long to charge or discharge the capacitor before executing rctime.
rctime ? basic stamp command reference page 366 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com so it takes only 110 s for the cap to charge/discharge, meaning that the 1 ms charge/discharge time of the example is plenty. a final note about figure 5.33: you may be wondering why the 220 ? resistor is necessary at all. consider what would happen if resistor r in figure 5.33a were a pot, and were adjusted to 0 ? . when the i/o pin went high to charge the cap, it would s ee a short direct to ground. the 220 ? series resistor would limit the short circuit current to 5v/220 ? = 23 ma and protect the basic stamp from damage. (actual current would be quite a bit less due to internal resistan ce of the pin?s output driver, but you get the idea.) demo program (rctime1.bs2) ' rctime1.bs2 ' this program shows the standard use of the rctime instruction measuring ' an rc charge/discharge time. use the circuit in the rctime description ' (in the manual) with r = 10k pot and c = 0.1 uf. connect the circuit to ' pin 7 and run the program. adjust the pot and watch the value shown on ' the debug screen change. ' {$stamp bs2} ' {$pbasic 2.5} rc pin 7 result var word main: do high rc ' charge the cap pause 1 ' for 1 ms rctime rc, 1, result ' measure rc discharge time debug home, dec result ' display value pause 50 loop end n otes about 220 ? resistor in the rc circuits . all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? rctime basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 367 figure 5.34: relay circuit for demo program rctime2.bs2. demo program (rctime2.bs2) ' rctime2.bs2 ' this program illustrates the use of rctime as a fast stopwatch. the ' program energizes a relay coil, then measures how long it takes for the ' relay contacts to close. the circuit for this program can be found in ' the manual. note that rctime doesn't start timing instantly -- as with ' all pbasic instructions, it must be fetched from program eeprom before ' it can execute. ' {$stamp bs2} ' {$pbasic 2.5} coil pin 6 rc pin 7 #select $stamp #case bs2, bs2e, bs2pe adjust con $200 ' x 2 us per unit #case bs2sx adjust con $0cc ' x 0.8 us per unit #case bs2p, bs2px adjust con $0c0 ' x 0.75 us per unit #endselect result var word main: do low coil ' energize relay coil rctime rc, 1, result ' measure time to contact closure result = result */ adjust ' adjust for device debug "time to close: ", relay contact relay coil 10 k ? p6 p7 vss vdd vdd relay: 5 vdc reed relay with 20 ma coil, eg., radio shack #275-232 all 2 note: this example program can be used with all bs2 models. this program uses conditional compilation techniques; see chapter 3 for more information.
rctime ? basic stamp command reference page 368 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com dec result, cr high coil ' release relay pause 1000 ' wait one second loop end
5: basic stamp command reference ? read basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 369 read bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px read location, variable read location, { word } variable {, { word } variable... } function read the value at location in eeprom and store the result in variable .  location is a variable/constant/expression (0 ? 255 on bs1, 0 ? 2047 on all bs2 models) that specifies the eeprom address to read from.  variable is a variable (usually a byte, or word when the optional word modifier is used) in which to store the value. quick facts table 5.88: read quick facts. bs1 bs2, bs2e, bs2sx bs2p, bs2pe, bs2px range of eeprom locations 0 to 255 0 to 2047 0 to 2047 (see notes below) special notes n/a read only works with current program slot on bs2e and bs2sx. read works with any program slot as set by the store command. related commands write and eeprom write and data write, data and store pbasic 2.5 syntax options n/a multiple sequential variables may be read from the scratch pad ram, and the optional word modifier may be specified to retrieve 16-bit values. explanation the eeprom is used for both progra m storage (which builds downward from address 255 on bs1, 2047 on a ll bs2 models) and data storage (which builds upward from address 0). the read instruction retrieves a value from any eeprom address and stores that value in variable . when the optional word modifier is used, the low byte of variable is read from location , the high byte of variable from location + 1. any location within the eeprom can be read (including your pbasic program's tokens) at run-time. this feature is mainly used to retrieve long-term data from eeprom; data stored in eeprom is not lost when the power is removed. note: expressions are not allowed as arguments on the bs1. 1 1 all 2 note: optional arguments require pbasic 2.5.
read ? basic stamp command reference page 370 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the following read command retrieves the value at location 100 and stores it into the variable called result : symbol result = b2 read 100, result --or-- result var byte read 100, result the eeprom is organized as a sequential set of byte-sized memory locations. the read command normally only retrieves byte-sized values from eeprom. this does not mean that you can't read word-sized values, however. a word consists of two bytes, called a low-byte and a high-byte. with pbasic 1.0 or 2.0, if you want to read a word-sized value, you'll need to use two read commands and a word-sized variable. symbol result = w0 symbol resltlo = b0 symbol reslthi = b1 eeprom (101, 4) read 0, resltlo 'read low byte read 1, reslthi 'read high byte debug #result --or-- result var word data word 1125 read 0, result.lowbyte 'read low byte read 1, result.highbyte 'read high byte on all bs2 models, by using the $pbasic 2.5 directive, you can use a single read command with the word modifier. for example, r eading word values vs . byte values . a simple read command . 1 all 2 1 all 2 note: this method is required only if using pbasic 2.0. see section below for pbasic 2.5 method.
5: basic stamp command reference ? read basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 371 ' {$pbasic 2.5} result var word data word 1125 read 0, word result debug dec ? result this code uses the eeprom or data directive to write the low-byte and high-byte of the number 1125 into locations 0 and 1 during download. the bs1 code the uses two read commands to read each of the bytes out of eeprom and reconstructs them into a single word-sized variable. pbasic 2.5 uses read?s optional wo rd modifier to read both bytes from eeprom and into a word-sized variable. both programs then display the value on the screen. when using pbasic 2.5, a single read command can retrieve multiple bytes and words from sequential eeprom locations. for example: ' {$pbasic 2.5} temp var byte temp2 var word read 25, temp, word temp2 ' retrieve byte from location 25 ' and word from locations 26 and 27 debug dec temp, cr ' display value of temp, carriage return debug dec temp2 ' display value of temp2 note that the eeprom and data directives store data in the eeprom before the program runs, however, the write command can be used to store data while the program is ru nning. additionally, the eeprom locations can be read an unlimite d number of times, but eeprom locations can be worn out by excess ive writes. see the write command for more information. when using the read and write comma nds, take care to ensure that your program doesn?t overwrite itself. on the bs1, location 255 holds the address of the last instruction in your program. therefore, your program can use any space below the address given in location 255. for example, if location 255 holds the value 100, then your program can use locations 0?99 for data. you can read location 255 at run-time or simply view the s pecial notes for eeprom usage . all 2 all 2
read ? basic stamp command reference page 372 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com memory map of the program before you download it. on all bs2 models you will need to view the memory map of the program before you download it, to determine the last eeprom location used. see the "memory map function" section in chapter 3. on the bs2p, bs2pe, and bs2px, the read and write commands can affect locations in any program slot as set by the store command. see the store command for more information. demo program (read.bs1) ' read.bs1 ' this program reads a string of data stored in eeprom. the eeprom data is ' downloaded to the bs1 at compile-time and remains there (even with the ' power off) until overwritten. put ascii characters into eeprom, followed ' by 0, which will serve as the end-of-message marker. for programs with ' multiple strings, use the memory map window to find the starting character ' address. ' {$stamp bs1} ' {$pbasic 1.0} symbol straddr = b2 symbol char = b3 msg1: eeprom ("bs1", 13, "eeprom storage!", 0) main: straddr = 0 ' set to start of message gosub string_out end string_out: read straddr, char ' read byte from eeprom straddr = straddr + 1 ' point to next character if char = 0 then strout_exit ' if 0, exit routine debug #@char ' otherwise print char goto string_out ' get next character strout_exit: return 1
5: basic stamp command reference ? read basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 373 demo program (read.bs2) ' read.bs2 ' this program reads a string of data stored in eeprom. the eeprom data is ' downloaded to the bs2 at compile-time and remains there (even with the ' power off) until overwritten. put ascii characters into eeprom, followed ' by 0, which will serve as the end-of-message marker. ' {$stamp bs2} ' {$pbasic 2.5} straddr var word char var byte msg1 data "bs2", cr, "eeprom storage!", 0 main: straddr = msg1 ' set to start of message gosub string_out end string_out: do read straddr, char ' read byte from eeprom straddr = straddr + 1 ' point to next character if (char = 0) then exit ' if 0, exit routine debug char ' otherwise print char loop return all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
read ? basic stamp command reference page 374 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? return basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 375 return bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px return function return from a subroutine, assumi ng there was a previous gosub executed. quick facts table 5.89: return quick facts. bs1 bs2 models related commands gosub gosub and on maximum number of returns per program unlimited. however, the number of gosubs are limited. see gosub for more information. explanation return sends the program back to the address (instruction) immediately following the most recent gosub. if return is executed without a prior gosub, the basic stamp will return to the first executable line of the program; usually resulting in a logical bug in the code. see the gosub command for more information. the example below will start out by gosub'ing to the section of code beginning with the label hello . it will print "hello, my friend!" on the screen then return to the line after the gosub? which prints "how are you?" and ends. main: gosub hello debug "how are you?" end hello: debug "hello, my friend!", cr return there's another interesting lesson here; what would happen if we removed the end command from this example? since the basic stamp reads the code from left to right / top to bottom (like the english language) once it had returned to and run the "how are you?" line, it would naturally "fall into" the hello routine again. additionally, at the end of the hello routine, w atch out for subroutines that your program can " fall into ." 1 a ll 2 note: on the bs1, a return without a gosub will return the program to the last gosub (or will end the program if no gosub was executed). 1
return ? basic stamp command reference page 376 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com it would see the return again (althoug h it didn't gosub to that routine this time) and because there wasn't a previous place to return to, the basic stamp will start the entire program over again. this would cause an endless loop. the important thing to remember here is to always make sure your program doesn't allow itself to "fall into" a subroutine. demo program (return.bs2) ' return.bs2 ' this program demonstrates a potential bug caused by allowing a program to ' "fall into" a subroutine. the program was intended to indicate that it ' is "starting...", then "executing subroutine,", then "returned..." from ' the subroutine and stop. since we left out the end command (indicated in ' the comments), the program then falls into the subroutine, displays ' "executing..." again and then returns to the start of the program and ' runs continuously in an endless loop. ' {$stamp bs2} reset: debug "starting program", cr ' show start-up main: pause 1000 gosub demo_sub ' call the subroutine pause 1000 debug "returned from subroutine", cr ' show that we're back pause 1000 ' <-- forgot to put end here demo_sub: debug " executing subroutine", cr ' show subroutine activity return 1 a ll 2 note: this example program can be used with the bs1 and all bs2 models by changing the $stamp directive accordin g l y .
5: basic stamp command reference ? reverse basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 377 reverse bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px reverse pin function reverse the data direction of the specified pin.  pin is a variable/constant/expression (0 ? 15) that specifies the i/o pin to use. this pin will be placed into the mode opposite its current input/output mode. quick facts table 5.90: reverse quick facts. bs1 and all bs2 models related commands input and output explanation reverse is a convenient way to switch the i/o direction of a pin. if the pin is an input, reverse makes it an output; if it?s an output, reverse makes it an input. remember that ?input? really has two meanings: (1) setting a pin to input makes it possible to check the state (1 or 0) of external circuitry connected to that pin. the current state is in th e corresponding bit of the ins register (pins on the bs1). (2) setting a pin to input also disconnects the output driver, the corresponding bit of outs (pins on the bs1). the demo program below illustrates this second fact with a two-tone led blinker. figure 5.35: led circuit for demo programs. r1 r2 220 led note: expressions are not allowed as arguments on the bs1. the range of the pin argument on the bs1 is 0 ? 7. 1 a ll 2 1
reverse ? basic stamp command reference page 378 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com demo program (reverse.bs1) ' reverse.bs1 ' connect the circuit shown in the reverse command description to i/o pin ' 0 and run this program. the led will alternate between two states, dim ' and bright. the basic stamp is using the reverse command to toggling i/o ' pin 0 between input and output states. when pin 0 is an input, current ' flows through r1, through the led, through r2 to ground. pin 0 is ' effectively disconnected and doesn't play a part in the circuit. the ' total resistance encountered by current flowing through the led is r1 + ' r2 = 1220 ohms. when pin 0 is reversed to an output, current flows ' through r1, through the led, and into pin 0 to ground (because of the 0 ' written to pin0). the total resistance encountered by current flowing ' through the led is r1,220 ohms. with only 20% of the resistance, the led ' glows brighter. ' {$stamp bs1} ' {$pbasic 1.0} setup: pin0 = 0 ' put a low in the pin 0 ' output driver main: pause 250 ' 1/4th second pause reverse 0 ' reverse pin 0 i/o direction goto main ' do forever demo program (reverse.bs2) ' reverse.bs2 ' connect the circuit shown in the reverse command description to i/o pin ' 0 and run this program. the led will alternate between two states, dim ' and bright. the basic stamp is using the reverse command to toggling i/o ' pin 0 between input and output states. when pin 0 is an input, current ' flows through r1, through the led, through r2 to ground. pin 0 is ' effectively disconnected and doesn't play a part in the circuit. the ' total resistance encountered by current flowing through the led is r1 + ' r2 = 1220 ohms. when pin 0 is reversed to an output, current flows ' through r1, through the led, and into pin 0 to ground (because of the 0 ' written to out0). the total resistance encountered by current flowing ' through the led is r1,220 ohms. with only 20% of the resistance, the led ' glows brighter. ' {$stamp bs2} ' {$pbasic 2.5} setup: out0 = 0 ' put a low in the pin 0 ' output driver 1 all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? reverse basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 379 main: pause 250 ' 1/4th second pause reverse 0 ' reverse pin 0 i/o direction goto main ' do forever
reverse ? basic stamp command reference page 380 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? run basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 381 run bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px run programslot function switches execution to another basic stamp program (in a different program slot).  programslot is a variable/constant/expression (0 ? 7) that specifies the program slot to run. quick facts table 5.91: run quick facts. bs2e bs2sx bs2p bs2pe bs2px time delay to switch between program slots 770 s 300 s 250 s 736 s 195 s related commands n/a pollrun special notes run is similar to a goto? you can not "return" from a run explanation the bs2e, bs2sx, bs2p, bs2pe and bs2px have a total of 16 k bytes of code space. this code space is organized into eight slots of 2 k bytes each. the bs2pe has 32 k of eeprom but only the first 16 k (eight slots) can be sued for programs. up to eight different programs can be downloaded to the basic stamp (one program per code slot). when the basic stamp powers up, or is reset, the program in slot 0 is executed. the run command allows you to acti vate another program and causes the basic stamp to stay in the newly activated program until it receives another run command, or until a power-down or reset condition occurs. the run command is similar to a goto command in that it allows you to "goto" another program. normally a master-type program will be used in program slot 0 (since slot 0 runs fi rst) and will control initial execution of the other programs. look at the following example (there are two programs here, make sure to download them into program slots 0 and 1, respectively. see the compiler directives section of chapter 3 for more information): a simple example of run.
run ? basic stamp command reference page 382 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com ' download this program to slot 0 debug "hello " run 1 ' download this program to slot 1 debug "world!" pause 1000 run 0 the above two programs (assuming they have been downloaded into program slots 0 and 1, respectively) will display "hello world!" on the screen. program 0 is the first to run an d it displays "hello ", then issues a run 1 command. the basic stamp then starts execution of program 1, from its first line of code, which causes "world!" to be displayed. program 1 then pauses for 1 second and the runs program 0 again. the i/o pins retain their current stat e (directions and output latches) and all ram and spram locations retain thei r current data during a transition between programs with the run command. if sharing data between programs within ram, make sure to keep similar variable declarations (defined in the same order) in all programs so that the variables align themselves on the proper word, byte, nibble and bit boundaries across programs. the following programs illustrate what happens with mismatched variable declarations: ' download this program to slot 0 cats var byte dogs var byte setup: cats = 3 dogs = 1 debug ? cats debug ? dogs run 1 ' download this program to slot 1 cats var byte dogs var byte fleas var word main: debug ? cats debug ? dogs debug ? fleas end w hat happens to i/o pins and ram when using run?
5: basic stamp command reference ? run basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 383 when the slot 1 program runs you may be surprised to see that cats and dogs are now zero and fleas are up to 259! ? even though we didn't explicitly define them. what happened? the key to remember is that variable names are simply pointers to ram addresses, and the pbasic compiler assigns variable names to ram in descending order by size. this means that in the slot 1 program, fleas was assigned to ram locations 0 and 1 which are holding the values 3 and 1 respectively. since words are stored low-byte first, the value 259 for fleas makes sense (3 + (1 * 256)). there may be occasions when you need to preserve the ram space in a program slot before calling on anothe r slot that has different variable requirements. you can use the following subroutines to save your ram space to the spram and restore it on returning from the other program slot. save_ram: put 0, b0 ' move ram 0 value to sp for b0 = 1 to 25 ' loop through other ram bytes put b0, b0(b0) ' move ram value to sp location next return restore_ram: for b0 = 1 to 25 ' loop through ram get b0, b0(b0) ' retrieve ram value from sp next get 0, b0 ' retrieve ram 0 value from sp return while the use of internal variable names is usually discouraged, these subroutines demonstrate a valid opportunity for their use, as well as the ability to take advantage of the basic stamp's unique memory architecture. the save_ram routine starts by savi ng the first byte of ram (internal name: b0) to location 0 in the spram. this is done so that b0 can be used as a loop index for the other location s. the for...next loop provides control of that index. the following line is probably the most difficult to comprehend, but works due to the na ture of the basic stamp module's ram organization put b0, b0(b0) ' move ram value to sp location
run ? basic stamp command reference page 384 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com in the basic stamp, the variable ram is implicitly considered an array. what this line is doing, then, is moving the value in each ram address (b0(1), b0(2), b0(3), ...) to the spram address that corresponds with its byte index. the process is simply reversed to retrieve the ram variable space. any programslot specified above 7 will wrap around and result in running one of the 8 programs (run 8 will run program 0, run 9 will run program 1, etc). review the advanced compilation tec hniques section beginning on page 68 for more information on do wnloading multiple programs. demo program (run1.bsx) ' run1.bsx ' this example demonstrates the use of the run command. first, the spram ' location that holds the current slot is read using the get command to ' display the currently running program number. then a set of values ' (based on the program number) are displayed on the screen. afterwards, ' program number 1 is run. this program is a bs2sx project consisting of ' run1.bsx and run2.bsx, but will run on all multi-slot basic stamp models. ' {$stamp bs2sx, run2.bsx} ' {$pbasic 2.5} #select $stamp ' set spram of slot number #case bs2 #error "multi-slot basic stamp required." #case bs2e, bs2sx slot con 63 #case bs2p, bs2pe, bs2px slot con 127 #endselect slotnum var nib ' current slot idx var nib ' loop counter value var byte ' value from eeprom eetable data 100, 40, 80, 32, 90 data 200, 65, 23, 77, 91 setup: get slot, slotnum ' read current slot debug "program #", dec slotnum, cr ' display main: note: this example program was written for the bs2sx but can be used with the bs2e, bs2p, bs2pe, and bs2px. this program uses conditional compilation techniques; see chapter 3 for more information.
5: basic stamp command reference ? run basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 385 for idx = 0 to 4 ' read/display table values read (slotnum * 5) + idx, value debug dec3 value, " " next debug cr pause 1000 run 1 ' run slot 1 pgm demo program (run2.bsx) ' run2.bsx ' this example demonstrates the use of the run command. first, the spram ' location that holds the current slot is read using the get command to ' display the currently running program number. then a set of values ' (based on the program number) are displayed on the screen. afterwards, ' program number 0 is run. this program is a bs2sx project consisting of ' run1.bsx and run2.bsx, but will run on all multi-slot basic stamp models. ' {$stamp bs2sx} ' {$pbasic 2.5} #select $stamp ' set spram of slot number #case bs2 #error "multi-slot basic stamp required." #case bs2e, bs2sx slot con 63 #case bs2p, bs2pe, bs2px slot con 127 #endselect slotnum var nib ' current slot idx var nib ' loop counter value var byte ' value from eeprom eetable data 100, 40, 80, 32, 90 data 200, 65, 23, 77, 91 setup: get slot, slotnum ' read current slot debug "program #", dec slotnum, cr ' display main: for idx = 0 to 4 ' read/display table values read (slotnum * 5) + idx, value debug dec3 value, " " next debug cr pause 1000 run 0 ' back to slot 0 pgm note: this example program was written for the bs2sx but can be used with the bs2e, bs2p, bs2pe, and bs2px. this program uses conditional compilation techniques; see chapter 3 for more information.
run ? basic stamp command reference page 386 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? select...case basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 387 select?case bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px select expression case condition(s) statement(s) { case condition(s) statement(s)... } { case else statement(s) } endselect function evaluate expression and conditionally execute a code block based on comparison to condition(s) then continue execution with line following endselect.  expression is a variable, a constant, or an expression.  condition is a statement that, when comapred to expression , can be evaluated as true or false. the condition can be a very simple or very complex relationship, as described below. multiple conditions within the same case can be separated by commas ( , ).  statement is any valid pbasic instruction. quick facts table 5.92: select...case quick facts. all bs2 models comparison operators =, <>, >, <, >=, <= conditional logic operators not allowed, however multiple conditions can be separated by commas (,) which act like a logical or operator. format of condition comparison value where value can by any of variable, constant or expression parentheses allowed to specify order of execution within expressions. maximum nested select statements 16 maximum cases per select 16 related commands if...then, on, and branch all 2 note: select...case requires pbasic 2.5.
select...case ? basic stamp command reference page 388 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com explanation select?case is an advanced decision-making structure that is often used to replace compound if?then?else structures. select?case statements are good for performing one of many possible actions depending on the value of a single expression. upon reaching a select?case statement, the basic stamp will evaluate expression once and then compare it to the condition(s) of each case until it finds a ?case? that evaluates to true, or it runs out of cases to compare to. as soon as a true case is found, the basic stamp executes that case?s statement(s) and then continues execution on the program line following endselect. to understand how select?case statements work, it helps to review how if?then statements behave. the condition argument of if?then takes the form: value1 comparison value2 and value1 is ?compared? to value2 using the comparison operator. in select...case statements, the value1 component is always expression and so the format of condition(s) is simplified to: { comparison } value comparison is optional and can be any of the comparison operators shown in table 5.93. if c omparison is not specified, it is an implied equal ( = ) operator. value can be a variable, constant or expression. comparison operator symbol definition = equal <> not equal > greater than < less than >= greater than or equal to <= less than or equal to table 5.93: comparison operators for select...case. condition(s) also has a special, additional format that can be used to indicate a range of sequential values:
5: basic stamp command reference ? select...case basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 389 value1 to value2 this indicates a range of value1 to value2, inclusive. for example, 20 to 23 means 20, 21, 22 and 23. similarly, ?a? to ?f? means all the characters in the range ?a? through ?f?. finally, multiple conditions can be included in a single case by separating them with commas ( , ). for example, case 20, 25 to 30, >100 will evaluate to true if the expression (from the select statement) is equal to 20, or is in the range 25 through 30, or is greater than 100. an example will help clarify this function. '{$pbasic 2.5} guess var word debug "guess my favorite number: " ' prompt user do debugin dec guess ' get answer select guess case < 100 ' less than 100? debug cr, "not even close. higher." case > 140 ' greater than 140? debug cr, "too high." case 100 to 120, 126 to 140 ' 100-120 or 126-140? debug cr, "getting closer..." case 123 ' 123? got it! debug cr, "that?s it! 123!" debug cr, "good guessing!" stop case 121 to 125 ' close to 123? debug cr, "you?re so close!" endselect debug cr, "try again: " ' encourage another try loop this program will ask the user to guess a number, store that value in guess and check the results in the select statement. if guess is less than 100, the first case is true and basic stamp will display ?not even close.
select...case ? basic stamp command reference page 390 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com higher.? then continues after the en dselect, displaying ?try again: ? on the screen and giving the user another guess. if guess is greater than 140, the second case is true, ?too high.? will be displayed followed by ?try again: ?, etc. if the user gue sses 123, they are congratulated and the program stops. you may have noticed a potential error in the code: both of the last two cases are true if guess is 123. so why didn?t the second case execute? the answer is because only the firs t ?true? case is executed and any further cases are ignored. if we had swapped the order of the last two cases, we?d have a bug in the progra m and the user would never find out that 123 was the correct number because ?case 123? would never have been evaluated. it?s not recommend to write code this way; ?case 121 to 122, 124 to 125? or even ?case 121, 122, 124, 125? would have been more clear and would prevent po tential bugs like this one. many situations call for special hand ling of a few cases and every other case is handled another way. there is a special form of case to handle this as well, called case else. in our example above, we could have replaced ?case 121 to 125? with ?case else? and it would behave exactly the same. case else is a way to ensure that every possible expression value is handled by a case; it?s like saying, ?if none of the previous cases were true, run this case.? for a select?case statement to work properly, it must have no more than one case else statement, and that case else statement must be the very last case. the condition(s) have a format similar to that of the if?then commands except, in select?case statements, expression is always implied as the first part of the condition. demo program (select-case.bs2) ' select-case.bs2 ' this program generates a series of 16-bit random numbers and tests each ' to determine odd or even, and where it falls in the possible range: ' lower third, middle third, or upper third. the program is useful for ' testing various seed values for random. ' {$stamp bs2} ' {$pbasic 2.5} all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? select...case basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 391 test var byte ' counter for tests sample var word ' random number to be tested odd var byte ' odd throws even var byte ' even throws islo var byte ' sample in lower third ismid var byte ' in middle thrid ishi var byte ' in upper third main: sample = 11000 ' initialize seed for test = 1 to 100 ' "throw" 100 times random sample ' randomize if (sample.bit0) then ' check odd/even bit odd = odd + 1 ' increment odd count else even = even + 1 ' increment even count endif select sample case <= 21845 ' test lower third islo = islo + 1 case 21846 to 43691 ' test middle third ismid = ismid + 1 case else ' otherwise upper third ishi = ishi + 1 endselect next show_results: debug cls, "odd throws.... ", dec odd, "%", cr, "even throws... ", dec even, "%", cr, "low........... ", dec islo, "%", cr, "mid........... ", dec ismid, "%", cr, "high.......... ", dec ishi, "%", cr end
select...case ? basic stamp command reference page 392 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? serin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 393 serin bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px serin rpin, baudmode, { ( qualifier ) , } { # } inputdata serin rpin { \ fpin } , baudmode, { plabel, } { timeout, tlabel, } [ inputdata ] function receive asynchronous serial data (e.g., rs-232 data).  rpin is a variable/constant/expression (0 ? 16) that specifies the i/o pin through which the serial data will be received. this pin will be set to input mode. on all bs2 models, if rpin is set to 16, the basic stamp uses the dedicated serial-i nput pin (sin, physical pin 2), which is normally used by the stamp editor during the download process.  fpin is an optional variable/constant/expression (0 ? 15) that specifies the i/o pin to indicate flow control status on. this pin will be set to output mode.  baudmode is variable/constant/expression (0 ? 7 on the bs1, 0 ? 65535 on all bs2 models) that specifies serial timing and configuration.  qualifier is an optional variable/constant (0 ? 255) indicating data that must be received before ex ecution can continue. multiple qualifiers can be indicated with commas separating them.  plabel is an optional label indicating where the program should go in the event of a parity error. this argument should only be provided if baudmode indicates 7 bits, and even parity.  timeout is an optional variable/constant/expression (0 ? 65535) that tells serin how long to wait for incoming data. if data does not arrive in time, the program will jump to the address specified by tlabel .  tlabel is an optional label that must be provided along with timeout , indicating where the program should go in the event that data does not arrive within the period specified by timeout .  inputdata is list of variables and formatters that tells serin what to do with incoming data. serin can store data in a variable or array, interpret numeric text (decimal, binary, or hex) and store the note: expressions are not allowed as arguments on the bs1. the range of the r p in argument on the bs1 is 0 ? 7. note: the bs1's inputdata argument can only be a list of variables and the optional decimal modifier (#). 1 all 2 1 1
serin - basic stamp command reference page 394 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com corresponding value in a variable , wait for a fixed or variable sequence of bytes, or ignore a specified number of bytes. these actions can be combined in any order in the inputdata list. quick facts bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px units in timeout n/a 1 ms 1 ms 0.4 ms 0.4 ms 1 ms 0.4 ms baud range 300, 600, 1200, and 2400 only 243 to 50k 243 to 50k 608 to 115.2k 608 to 115.2k 243 to 50k 972 to 115.2k baud limit with flow control n/a 19.2k 19.2k 19.2k 19.2k 19.2k 19.2k limit to qualifiers unlimited 6 (in wait formatter) i/o pins available 0 - 7 0 ? 15 0 - 15 0 ? 15 0 ? 15 (in current i/o block) 0 ? 15 (in current i/o block) 0 ? 15 (in current i/o block) other serial port pins n/a sin pin (physical pin 2) when rpin = 16 related command serout serout and debugin table 5.94: serin quick facts. explanation one of the most popular forms of communication between electronic devices is serial communication. th ere are two major types of serial communication; asynchronous and synchronous. the serin and serout commands are used to receive and send asynchronous serial data. see the shiftin and shiftout command for information on the synchronous method. serin can wait for, filter and conver t incoming data in powerful ways. serin deserves some lengthy discussion, below, since all this power brings some complexity. the term asynchronous means ?no clock.? more specifically, "asynchronous serial communication " means data is transmitted and received without the use of a separate "clock" wire. data can be sent using as little as two wires; one for data and one for ground. the pc's serial ports (also called com ports or rs-2 32 ports) use asynchronous serial communication. note: the other ki nd of serial communication, synchronous, uses at least three wires; one for clock, one for data and one for ground. s erial communication background . p hysical and electrical details .
5: basic stamp command reference ? serin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 395 rs-232 is the electrical specification for the signals that pc serial ports use. unlike normal logic, where 5 volts is a logic 1 and 0 volts is logic 0, rs-232 uses -12 volts for logic 1 and +12 volts fo r logic 0. this specification allows communication over longer wire lengths without amplification. most circuits that work with rs-232 use a line driver/receiver. this component does two things: (1) it converts the 12 volts of rs-232 to ttl-compatible 0 to 5-volt levels and (2 ) it inverts the relationship of the voltage levels, so that 5 volts = logic 1 and 0 volts = logic 0. all bs2 models have a line receiver on its sin pin ( rpin = 16). see the "introduction to the basic stamp" chapter. the sin pin goes to a pc?s serial data-out pin on the db9 connector built into basic stamp development boards. the connector is wired to allow both programming and run-time serial communicatio n (unless you are using the basic stamp 2 carrier board (#27120) which is designed for programming only). for the built-in serial port set the rpin argument to 16 in the serin command. all basic stamp models (including the bs1) can also rece ive rs-232 data through any of their i/o pins ( rpin = 0 ? 7 for bs1, rpin = 0 ? 15 on all bs2 models). the i/o pins don?t need a line receiver, just a 22 k ? resistor. the resistor limits current into the i/o pins? built-in clamping diodes, which keep input voltages within a safe range. see figure 5.36. figure 5.36: serial port diagram showing correct connections to a basic stamp's i/o pin. note: the 22 k ? resistor is not required if connecting to the sin pin. db-9 male (connector side) to i/o pin 22 k ? 2 3 4 transmit data (td) receive data (rd) request to send (rts) 6 7 20 data set ready (dsr) signal ground (sg) data terminal ready (dtr) 3 2 7 6 5 4 db25 function db9 note: the connections shown with double-lines are normally not necessary. they indicate optional connections to disable hardware handshaking (dtr-dsr-dcd and rts-cts). this is only necessary if you are using software or hardware that expects hardware handshaking. db-25 male (connector side) 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 9 8 7 6 5 4 3 2 1 vss to i/o pin 22 k ? vss 8 data carrier detect (dcd) 1 5 clear to send (cts) 8 u sing the built - in serial port on all bs2 models . all 2 1 a ll 2
serin - basic stamp command reference page 396 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com figure 5.36 shows the pinouts of the tw o styles of pc serial ports and how to connect them to the basic stamp's i/o pin (the 22 k ? resistor is not needed if connecting to the sin pin). though not normally needed, the figure also shows loop back co nnections that defeat hardware handshaking used by some pc software. note that pc serial ports are always male connectors. the 25-pin style of serial port (called a db25) looks similar to a printer (parallel) po rt except that it is male, whereas a parallel port is female. asynchronous serial communication relies on precise timing. both the sender and receiver must be set for identical timing, usually expressed in bits per second (bps) called baud. on all basic stamp models, serin requires a value called baudmode that tells it the important characteristics of the incoming serial data; the bit period, number of data and parity bits, and polarity. on the bs1, serial communication is limited to: no-parity, 8-data bits and 1-stop bit at one of four different speeds: 300, 600, 1200 or 2400 baud. table 5.95 indicates the baudmode value or symbols to use when selecting the desired mode. baudmode value symbol baud rate polarity 0 t2400 2400 true 1 t1200 1200 true 2 t600 600 true 3 t300 300 true 4 n2400 2400 inverted 5 n1200 1200 inverted 6 n600 600 inverted 7 n300 300 inverted table 5.95: bs1 baudmode values. on all bs2 models, serial communication is very flexible. the baudmode argument for serin accepts a 16-bit value that determines its characteristics: 1-stop bit, 8-data bits /no-parity or 7-data bits/even-parity and virtually any speed from as low as 300 baud to greater than 100k baud (depending on the basic stamp). table 5.96 shows how baudmode is calculated, while table 5.97, table 5.98, and table 5.99 show common baud modes for standard serial baud rates. s erial timing and mode ( baudmode ). 1 a ll 2 1 all 2
5: basic stamp command reference ? serin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 397 table 5.96: baudmode calculation for all bs2 models. add the results of steps 1, 2 and 3 to determine the proper value for the baudmode argument. step 1: determine the bit period (bits 0 ? 11). bs2, bs2e and bs2pe: = int(1,000,000 / baud rate) ? 20 bs2sx and bs2p: = int(2,500,000 / baud rate) ? 20 bs2px: = int(4,000,000 / baud rate) ? 20 note: int means 'convert to integer;' drop the numbers to the right of the decimal point. step 2: set data bits and parity (bit 13). 8-bit/no-parity = 0 7-bit/even-parity = 8192 step 3: select polarity (bit 14). true (noninverted) = 0 inverted = 16384 table 5.97: bs2, bs2e, and bs2pe common baud rates and corresponding baudmodes . baud rate 8-bit no-parity inverted 8-bit no-parity true 7-bit even-parity inverted 7-bit even-parity true 300 19697 3313 27889 11505 600 18030 1646 26222 9838 1200 17197 813 25389 9005 2400 16780 396 24972 8588 4800* 16572 188 24764 8380 9600* 16468 84 24660 8276 *the bs2, bs2e and bs2pe may have trouble synchroni zing with the incoming serial stream at this rate and higher due to the lack of a hard ware input buffer. use only simple variables and no formatters to try to solve this problem. table 5.98: bs2sx and bs2p common baud rates and corresponding baudmodes. baud rate 8-bit no-parity inverted 8-bit no-parity true 7-bit even-parity inverted 7-bit even-parity true 1200 18447 2063 26639 10255 2400 17405 1021 25597 9213 4800* 16884 500 25076 8692 9600* 16624 240 24816 8432 *the bs2sx and bs2p may have trouble synchronizing with the incoming serial stream at this rate and higher due to the lack of a hardware input buffer. use only simple variables and no formatters to try to solve this problem. table 5.99: bs2px common baud rates and corresponding baudmodes. baud rate 8-bit no-parity inverted 8-bit no-parity true 7-bit even-parity inverted 7-bit even-parity true 1200 19697 3313 27889 11505 2400 18030 1646 26222 9838 4800 17197 813 25389 9005 9600 16780 396 24792 8588 if you?re communicating with existing software or hardware, its speed(s) and mode(s) will determine your choice of baud rate and mode. in general, 7-bit/even-parity (7e) mode is used for text, and 8-bit/no-parity (8n) for byte-oriented data. note: the most common mode is 8-bit/no-parity, even when the data tr ansmitted is just text. most devices c hoosing the proper baud mode .
serin - basic stamp command reference page 398 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com that use a 7-bit data mode do so in order to take advantage of the parity feature. parity can detect some communication errors, but to use it you lose one data bit. this means that in coming data bytes transferred in 7e (even-parity) mode can only represent values from 0 to 127, rather than the 0 to 255 of 8n (no-parity) mode. usually a device requires only 1 stop bit per byte. occasionally, however, you may find a device that requires 2 or more stop bits. since a stop bit is really just a delay between transmitte d bytes (leaving the line in a resting state) the basic stamp can receive transmissions with multiple stop bits per byte without any trouble. in fact , sometimes it is desirable to have multiple stop bits (see the ?serin troubleshooting? section, below, for more information). the example below will receive a single byte through i/o pin 1 at 2400 baud, 8n1, inverted: symbol serdata = b2 serin 1, n2400, serdata --or-- serdata var byte serin 1, 16780, [serdata] here, serin will wait for and receive a single byte of data through pin 1 and store it in the variable serdata . if the basic stamp were connected to a pc running a terminal program (set to the same baud rate) and the user pressed the "a" key on the keyboard, after the serin command executed, the variable serdata would contain 65, the ascii code for the letter "a" (see the ascii character chart in appendix a). what would happen if, using the exampl e above, the user pressed the "1" key? the result would be that serdata would contain the value 49 (the ascii code for the character "1"). this is a critical point to remember: every time you press a character on the keyboard, the computer receives the ascii value of that character. it is up to the receiving side (in serial communication) to interpret the values as necessary. in this case, perhaps we actually wanted serdata to end up with the value 1, rather than the ascii code 49. a simple form of serin. a simple numeric conversion ; ascii text to decimal . note: this is written with the bs2's baudmode value. be sure to adjust the value for your basic stamp model. all 2 1
5: basic stamp command reference ? serin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 399 the serin command provides a formatter, called the decimal formatter, which will interpret this for us. look at the following code: symbol serdata = b2 serin 1, n2400, #serdata -- or -- serdata var byte serin 1, 16780, [dec serdata] notice the decimal formatter in the serin command. it is the ?#? (for the bs1) or ?dec? (for all bs2 models) that appears just to the left of the serdata variable. this tells serin to co nvert incoming text representing decimal numbers into true-decimal form and store the result in serdata . if the user running the terminal software pressed the "1", "2" and then "3" keys followed by a space or other non- numeric text, the va lue 123 will be stored in serdata . afterwards, the program can perform any numeric operation on the number just like with any other number. without the decimal formatter, however, you would have been forced to receive each character (?1?, ?2? and ?3?) separately, and then would still have to do some manual conversion to arrive at the number 123 (one hundred twenty three) before you can do the desired calculations on it. the decimal formatter is designed to se ek out text that represents decimal numbers. the characters that represent decimal numbers are the characters ?0? through ?9?. once the serin command is asked to use the decimal formatter for a particular variab le, it monitors the incoming serial data, looking for the first decimal charac ter. once it finds the first decimal character, it will continue looking fo r more (accumulating the entire multi- digit number) until is finds a non-decimal numeric character. keep in mind that it will not finish until it finds at least one decimal character followed by at least one non-decimal character. to further illustrate this, consider the following examples (assuming we?re using the same code example as above): 1) serial input: abc result: the basic stamp halts at the serin command, continuously waiting for decimal text. d ecimal formatter specifics . note: this is written with the bs2's baudmode value. be sure to adjust the value for your basic stamp. 1 all 2
serin - basic stamp command reference page 400 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com 2) serial input: 123 (with no characters following it) result: the basic stamp halts at the serin command. it recognizes the characters ?1?, ?2? and ?3? as the number one hundred twenty three, but since no characters follow the ?3?, it waits continuously, since there?s no way to tell whether 123 is the entire number or not. 3) serial input: 123 (followed by a space character) result: similar to example 2, above, except once the space character is received, the basic stamp knows the entire number is 123, and stores this value in serdata . the serin command then ends, allowing the next line of code, if any, to run. 4) serial input: 123a result: same as example 3, above. the ?a? character, just like the space character, is the first non-de cimal text after the number 123, indicating to the basic stamp that it has received the entire number. 5) serial input: abcd123efgh result: similar to examples 3 and 4 above. the characters ?abcd? are ignored (since they?re not decimal text), the characters ?123? are evaluated to be the number 123 and the following character, ?e?, indicate s to the basic stamp that it has received the entire number. for examples of all form atters and how they process incoming data, see appendix c. of course, as with all numbers in the basic stamp, the final result is limited to 16 bits (up to the number 6553 5). if a number larger than this is received by the decimal formatter, th e end result will look strange because the result rolled-over the maximum 16-bit value. the bs1 is limited to the decimal formatter shown above, however all the bs2 models have many more conver sion formatters available for the serin command. if not using a bs1, see the ?additional conversion formatters? section below for more information. w atch out for rollover errors .
5: basic stamp command reference ? serin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 401 the serin command can also be configured to wait for specified data before it retrieves any additional input. for example, suppose a device that is attached to the basic stamp is known to send many different sequences of data, but the only data you desire happens to appear right after the unique characters, ?xyz?. the bs1 has optional qualifier arguments for this purpose. on all bs2 models, a special formatter called wait can be used for this. symbol serdata = b2 serin 1, n2400, ("xyz"), #serdata -- or -- serdata var byte serin 1, 16780, [wait("xyz"), dec serdata] the above code waits for the characters ?x?, ?y? and ?z? to be received, in that order, and then it looks for a decimal number to follow. if the device in this example were to send the characters ?xyz100? followed by a carriage return or some other non-decimal numeric character, the serdata variable would end up with the number 100 after the serin line finishes. if the device sent some data other than ?xyz? followed by a number, the basic stamp would continue to wait at the serin command. the bs1 will accept an unlimited number of qualifiers . all bs2 models will only accept up to six bytes (characters) in the wait formatter. keep in mind that when we type ?xyz? into the serin command, the basic stamp actually uses the ascii codes for each of those characters for its tasks. we could also have typed: 88, 89, 90 in place of ?xyz? and the code would run the same way since 88 is the ascii code for the ?x? character, 89 is the ascii code for the ?y? character, and so on. also note, serial communication with the basic stam p is case sensitive. if the device mentioned above sent, ?xyz? or ?xyz ?, or some other combination of lower and upper-case characters, the basic stamp would have ignored it because we told it to look for ?xyz? (all capital letters). the bs1?s serin command is limited to above-mentioned features. if you are not using a bs1, please continue reading about the additional features below. u sing serin to wait for specific data before processing . u sing ascii codes and case sensitivity . all 2 this is written with the bs2's baudmode value. be sure to adjust the value for your basic stamp. 1 1
serin - basic stamp command reference page 402 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the decimal formatter is only one of a whole family of conversion formatters available with serin on all the bs2 models. see table 5.100 for a list of available conversion formatte rs. all of the conversion formatters work similar to the decimal formatter (as described in the ?decimal formatter specifics? section, above). the formatters receive bytes of data, waiting for the first byte that falls within the range of characters they accept (e.g., ?0? or ?1? for binary, ?0? to ?9? for decimal, ?0? to ?9? and ?a? to ?f? for hex, and ?-? for signed variations of any type). once they receive a numeric character, they keep accepting input until a non- numeric character arrives or (in the case of the fixed length formatters) the maximum specified number of digits arrives. a dditional conversion formatters . all 2
5: basic stamp command reference ? serin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 403 table 5.100: conversion formatters for all bs2 models. conversion formatter type of number numeric characters accepted notes dec{1..5} decimal, optionally limited to 1 ? 5 digits 0 through 9 1 sdec{1..5} signed decimal, optionally limited to 1 ? 5 digits -, 0 through 9 1,2 hex{1..4} hexadecimal, optionally lim ited to 1 ? 4 digits 0 through 9, a through f 1,3,5 shex{1..4} signed hexadecimal, optionally limited to 1 ? 4 digits -, 0 through 9, a through f 1,2,3 ihex{1..4} indicated hexadecimal, optionally limited to 1 ? 4 digits $, 0 through 9, a through f 1,3,4 ishex{1..4} signed, indicated hexadecimal, optionally limited to 1 ? 4 digits -, $, 0 through 9, a through f 1,2,3,4 bin{1..16} binary, optionally limited to 1 ? 16 digits 0, 1 1 sbin{1..16} signed binary, optionally limited to 1 ? 16 digits -, 0, 1 1,2 ibin{1..16} indicated binary, optionally limited to 1 ? 16 digits %, 0, 1 1,4 isbin{1..16} signed, indicated binary, optionally limited to 1 ? 16 digits -, %, 0, 1 1,2,4 num generic numeric input (decimal, hexadecimal or binary); hexadecimal or binary number must be indicated $, %, 0 through 9, a through f 1, 3, 4 snum similar to num with value treated as signed with range -32768 to +32767 -, $, %, 0 through 9, a through f 1,2,3,4 1 all numeric conversions will continue to accept new data until receiving either the specified number of digits (ex: three digits fo r dec3) or a non-numeric character. 2 to be recognized as part of a number, the minus sign (-) must immediately precede a numeric character. the minus sign character occurring in non-numeric text is ignored and any character (including a space) between a minus and a number causes the minus to be ignored. 3 the hexadecimal formatters are not case-sensi tive; ?a? through ?f? means the same as ?a? through ?f?. 4 indicated hexadecimal and binary formatters ignore all characters, even valid numerics, until they receive the appropriate prefix ($ fo r hexadecimal, % for bi nary). the indicated formatters can differentiate between text and hexadecimal (ex: abc would be interpreted by hex as a number but ihex would ignore it unless expressed as $abc). likewise, the binary version can dist inguish the decimal number 10 fr om the binary number %10. a prefix occurring in non-numeric text is i gnored, and any character (including a space) between a prefix and a number causes the prefix to be ignored. indicated, signed formatters require that the minus sign come before the prefix, as in -$1b45. 5 the hex modifier can be used for decimal to bcd conversion. see ?hex to bcd conversion? on page 97. for examples of all conversion formatters and how they process incoming data, see appendix c.
serin - basic stamp command reference page 404 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com while very effective at filtering and converting input text, the formatters aren?t completely foolproof. as mentioned before, many conversion formatters will keep accepting text unt il the first non-numeric text arrives, even if the resulting value exceeds the size of the variable. after serin, a byte variable will contain the lowest 8 bits of the value entered and a word would contain the lowest 16 bits. you can control this to some degree by using a formatter that specifies the number of digits, such as dec2, which would accept values only in the range of 0 to 99. all bs2 models also have special fo rmatters for handling a string of characters, a sequence of characters and undesirable characters. see table 5.101 for a list of these special formatters. also, see appendix c for example serial inputs and the result of using these formatters. special formatter action str bytearray \l {\e} input a character string of length l into an array. if specified, an end character e causes the string input to end before reaching length l. remaining byte s are filled with 0s (zeros). wait ( value) wait for a sequence of bytes specified by value. value can be numbers separated by commas or quoted text (ex: 65, 66, 67 or ?abc?). the wait formatter is limited to a maximum of six characters. waitstr bytearray {\l} wait for a sequence of bytes matching a string stored in an array variable, optionally limited to l characters. if the optional l argument is left off, the end of the array-string must be marked by a byte containing a zero (0). skip length ignore length bytes of characters. table 5.101: serin special formatters for all bs2 models. there is an additional special formatter for the bs2p, bs2pe, and bs2px, shown below. special formatter action spstr l input a character string of l bytes (up to 126) into scratch pad ram, starting at location 0. use get to retrieve the characters. table 5.102: additional serin special formatter for the bs2p, bs2pe, and bs2px. the string formatter is useful for receiving a string of characters into a byte array variable. a string of characters is a set of characters that are arranged or accessed in a certain or der. the characters "abc" could be stored in a string with the "a" first, followed by the "b" and then followed by the "c." a byte array is a similar concept to a string; it contains data that is arranged in a certain order. each of the elements in an array is the same size. the string "abc" could be stored in a byte array containing o nce again , pay attention to potential rollover errors . t he str ( string ) formatter .
5: basic stamp command reference ? serin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 405 three bytes (elements). see the "defining arrays" section in chapter 4 for more information on arrays. here is an example that receives nine bytes through i/o pin 1 at 9600 bps, n81/inverted and stores th em in a 10-byte array: serstr var byte(10) ' make 10-byte array serstr(9) = 0 ' put 0 in last byte of array serin 1, 16468, [str serstr\9] ' get nine bytes debug str serstr ' display why store only 9 bytes in a 10-byte a rray? we want to reserve space for the 0 byte that many basic stamp string-handling routines regard as an end-of-string marker. this becomes important when dealing with variable-length arrays. for example, the str formatter (see table 5.101) can accept an additional parameter telling it to end the string when a particular byte is received, or when the specified length is reached, whichever comes first. an example: serstr var byte(10) ' make 10-byte array serstr(9) = 0 ' put 0 in last byte of array serin 1, 16468, [str serstr\9\"*"] ' stop at "*" or nine bytes debug str serstr ' display if the serial input were "hello*" debug would display "hello" since it collects bytes up to (but no t including) the end character. it fills the unused bytes up to the specified length with 0s. debug?s normal str formatter understands a 0 to mean end-of-string. however, if you use debug?s fixed-length string modifier, str bytearray \l, you will inadvertently clear the debug screen. the fixed-length specification forces debug to read and process the 0s at the end of the string, and 0 is equivalent to debug?s cls (clear-screen) control character! be alert for the consequences of mixing fixed- and variable-l ength string operations. as shown before, serin can compare incoming data with a predefined sequence of bytes using the wait formatter. the simplest form waits for a sequence of up to six bytes specified as part of the inputdata list, like so: serin 1, 16468, [wait("sesame")] debug "password accepted." serin will wait for that word, and th e program will not continue until it is received. since wait is looking for an exact match for a sequence of m atching a sequence of characters with wait. note: the rest of the code examples for this section are written for the bs2, using the bs2's baudmode and timeout values. be sure to adjust the value for your basic stamp. all 2 all 2 all 2
serin - basic stamp command reference page 406 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com bytes, it is case-sensitive??sesame? or ?sesame? or any other variation from ?sesame? would be ignored. serin can also wait for a sequence that matches a string stored in an array variable with the waitstr formatter. in the example below, we?ll capture a string with str then have wait str look for an exact match: serstr var byte(10) ' make 10-byte array serstr(9) = 0 ' put 0 in last byte of array serin 1, 16468, [str serstr\9\"!"] ' get the string debug "waiting for:", str serstr, cr serin 1, 16468, [waitstr serstr] ' wait for match debug "password accepted." you can also use waitstr with fixed- length strings as in the following example: serstr var byte(4) ' make 4-byte array debug "enter 4-character password" serin 1, 16468, [str serstr\4] ' get the string debug "waiting for:", str serstr\4, cr serin 1, 16468, [waitstr serstr\4] ' wait for match debug "password accepted." serin?s inputdata can be structured as a sophisticated list of actions to perform on the incoming data. this allows you to process incoming data in powerful ways. for example, suppose you have a serial stream that contains ?pos: xxxx yyyy? (where xxxx and yyyy are 4-digit numbers) and you want to capture just the decima l y value. the following code would do the trick: yoffset var word serin 1, 16468, [wait("pos: "), skip 4, dec4 yoffset] debug ? yoffset the items of the inputdata list work together to locate the label ?pos: ?, skip over the four-byte x data, then convert and capture the decimal y data. this sequence assumes that the x da ta is always four digits long; if its length varies, the following code would be more appropriate: yoffset var word serin 1, 16468, [wait("pos: "), dec yoffset, dec4 yoffset] debug ? yoffset m atching a sequence of characters with waitstr. b uilding compound i nput d ata statements . all 2 all 2 all 2 all 2
5: basic stamp command reference ? serin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 407 the unwanted x data is stored in yoffset then replaced by the desired y data. this is a sneaky way to filter ou t a number of any size without using an extra variable. with a little creativity, you can combine the inputdata modifiers to filter and ex tract almost any data. parity is a simple error-checking feature. when a serial sender is set for even parity (the mode the basic stam p supports) it counts the number of 1s in an outgoing byte and uses the parity bit to make that number even. for instance, if it is sending the 7-bit value: %0011010, it sets the parity bit to 1 in order to make an even number of 1s (four). the receiver also counts the data bi ts to calculate what the parity bit should be. if it matches the parity bi t received, the serial receiver assumes that the data was received correctly. of course, this is not necessarily true, since two incorrectly received bits could make parity seem correct when the data was wrong, or the parity bit itself could be bad when the rest of the data was ok. many systems that work exclusively wi th text use (or can be set for) 7- bit/even-parity mode. table 5.97 and table 5.98 show appropriate baudmode settings for different basic stamp models. for example, with the bs2, to receive one data byte thro ugh pin 1 at 9600 baud, 7e, inverted: serdata var byte serin 1, 24660, [serdata] that instruction will work, but it does n?t tell the bs2 what to do in the event of a parity error. here?s an improved version that uses the optional plabel argument: serdata var byte main: serin 1, 24660, bad_data, [serdata] debug ? serdata stop bad_data: debug "parity error." stop if the parity matches, the program continues at the debug instruction after serin. if the parity doesn?t match, the program goes to the label u sing parity and handling parity errors . all 2 all 2
serin - basic stamp command reference page 408 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com bad_data. note that a parity error takes precedence over other inputdata specifications (as soon as an error is detected, serin aborts and goes to the plabel routine). in all the examples above, the only way to end the serin instruction (other than reset or power-off) is to give serin the serial data it wants. if no serial data arrives, the progra m is stuck. however, you can tell the basic stamp to abort serin if it does n?t receive a byte within a specified number of milliseconds. for instance, to receive a decimal number through pin 1 at 9600 baud, 8n, inverted and abort serin after 2 seconds (2000 ms) of inactivity on the serial input: result var word main: serin 1, 16468, 2000, no_data, [dec result] debug cls, ? result stop no_data: debug cls, "timeout error" stop if no data arrives within 2 seconds, the program aborts serin and continues at the label no_data . note that on multi-byte input, the timeout timer is reset after the receipt of an y valid data byte; with long timeout values this factor could have an ad verse affect on program operation if data packets are transmitted with gaps between individual data bytes. finally, be cautious when using ve ry short timeout values. without external flow control, very short ti meout values may cause the program to branch to the tlabel address unnecessarily. here's a very important concept: this timeout feature is not picky about the kind of data serin receives; if any serial data is received, it prevents the timeout. in the example above, serin wants a decimal number. but even if serin received letters ?abcd...? at intervals of less than two seconds, it would never abort. you can combine parity and serial ti meouts. here is an example for the bs2 designed to receive a decimal number through pin 1 at 9600 baud, 7e, inverted with a 10-second timeout: u sing the serial time - out feature . r emember : t imeout does not care what kind of data is received , only that data is received or not ! c ombining parity and time - out . all 2
5: basic stamp command reference ? serin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 409 ' {$pbasic 2.5} result var word main: do serin 1, 24660, bad_data, 10000, no_data, [dec result] debug cls, ? result loop bad_data: debug cls, "parity error" goto main no_data: debug cls, "timeout error" goto main when you design an application th at requires serial communication between basic stamp modules, yo u have to work within these limitations: ? when the basic stamp is sending or receiving data, it can?t execute other instructions. ? when the basic stamp is executing other instructions, it can?t send or receive data. the basic stamp does not have a serial buffer as there is in pcs. at most serial rates, the basic stamp cannot receive data via serin, process it, and execute another serin in time to catch the next chunk of data, unless there are significant pauses between data transmissions. these limitations can sometimes be ad dressed by using flow control; the fpin option for serin and serout (at baud rates of up to the limitation shown in table 5.94). through fpin , serin can tell a basic stamp sender when it is ready to receive data. (for that matter, fpin flow control follows the rules of other serial handshakin g schemes, but most computers other than the basic stamp cannot start and stop serial transmission on a byte- by-byte basis. that?s why this disc ussion is limited to communication between basic stamp modules.) here?s an example using flow control on the bs2 (data through i/o pin 1, flow control through i/o pin 0, 9600 baud, n8, noninverted): serdata var byte serin 1\0, 84, [serdata] c ontrolling data flow . all 2 all 2
serin - basic stamp command reference page 410 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com when serin executes, i/o pin 1 ( rpin ) is made an input in preparation for incoming data, and i/o pin 0 ( fpin ) is made output low, to signal ?go? to the sender. after serin finishes rece iving, i/o pin 0 goes high to tell the sender to stop. if an inverted baudmode had been specified, the fpin?s responses would have been reversed. here?s the relationship of serial polarity to fpin states. ready to receive ("go") not ready to receive ("stop") inverted fpin is high (1) fpin is low (0) non-inverted fpin is low (0) fpin is high (1) table 5.103: flow control pin states in relation to polarity (inverted or non-inverted) for all bs2 models. see the demo program, below, for a fl ow control example using two bs2s. in the demo program example, withou t flow control, the sender would transmit the whole word ?hello!? in about 6 ms. the receiver would catch the first byte at most; by the time it got back from the first 1-second pause, the rest of the data would be long gone. with flow control, communication is flawless since the sender waits for the receiver to catch up. in figure 5.37, i/o pin 0, fpin , is pulled to ground through a 10k resistor. this is to ensure that the sender sees a stop signal (0 for inverted communications) when the receiver is being programmed. p0 p1 vss bs2 sender p0 p1 bs2 receiver host pc (f or debug) programming cable vss 10k figure 5.37: flow-control example circuit. serial communication, because of its complexity, can be very difficult to work with at times. please follow these guidelines when developing a project using the serin and serout commands: 1. always build your project in steps. a. start with small, manageable pieces of code, that deals with serial communication) and test them, one at a time. serin t roubleshooting .
5: basic stamp command reference ? serin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 411 b. add more and more small pieces, testing them each time, as you go. c. never write a large portion of code that works with serial communication without testing its smallest workable pieces first. 2. pay attention to timing. a. be very careful to calculate and overestimate the amount of time operations should ta ke within the basic stamp. misunderstanding the timing co nstraints is the source of most problems with code that communicate serially. b. if the serial communication in your project is bi- directional, the above statement is even more critical. 3. pay attention to wiring. a. take extra time to study and verify serial communication wiring diagrams. a mistake in wiring can cause strange problems in communication, or no communication at all. make sure to connect the gr ound pins (vss) between the devices that are commu nicating serially. 4. verify port setting on the pc and in the serin/serout commands. a. unmatched settings on the send er and receiver side will cause garbled data transfers or no data transfers. if the data you receive is unreadable, it is most likely a baud rate setting error. 5. if receiving data from another device that is not a basic stamp, try to use baud rates of 4800 and below. a. because of additional overhead in the basic stamp, and the fact that the basic stamp has no hardware receive buffer for serial communication, received data may sometimes be missed or garbled. if this occurs, try lowering the baud rate (if possi ble), adding extra stop bits, and not using formatters in the serin command. using simple variables (not arrays ) and no formatters will increase the chance that the basic stamp can receive the data properly. 6. be sure to study the effects of serin formatters. a. some formatters have specific requirements that may cause problems in received data. for example, the dec formatter requires a non-decimal-numeric character to follow the received number before it will allow the basic
serin - basic stamp command reference page 412 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com stamp to continue. see appendix c for example input data and the effects on formatters. demo program (serin.bs1) ' serin.bs1 ' this program waits for the characters "a", "b", "c", and "d" to arrive ' at the serial input (inverted, 2400 baud, n81), followed by a number, ' then a carriage-return or some other non-number character. the number is ' then displayed in the debug window. ' {$stamp bs1} ' {$pbasic 1.0} symbol sin = 0 symbol baud = n2400 symbol result = w1 main: serin sin, baud, ("abcd"), #result debug #result, cr goto main end demo program (serin_serout1.bs2) ' serin_serout1.bs2 ' using two bs2-ic's, connect the circuit shown in the serin command ' description and run this program on the basic stamp designated as the ' sender. this program demonstrates the use of flow control (fpin). ' without flow control, the sender would transmit the whole word "hello!" ' in about 1.5 ms. the receiver would catch the first byte at most; by the ' time it got back from the first 1-second pause, the rest of the data ' would be long gone. with flow control, communication is flawless since ' the sender waits for the receiver to catch up. ' {$stamp bs2} ' {$pbasic 2.5} so pin 1 ' serial output fc pin 0 ' flow control pin #select $stamp #case bs2, bs2e, bs2pe t1200 con 813 t2400 con 396 t9600 con 84 t19k2 con 32 1 note: this example program was written for the bs2 but it can be used with the bs2e, bs2sx, bs2p, bs2pe, and bs2px. this program uses conditional compilation techniques; see chapter 3 for more information. all 2
5: basic stamp command reference ? serin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 413 t38k4 con 6 #case bs2sx, bs2p t1200 con 2063 t2400 con 1021 t9600 con 240 t19k2 con 110 t38k4 con 45 #case bs2px t1200 con 3313 t2400 con 1646 t9600 con 396 t19k2 con 188 t38k4 con 84 #endselect inverted con $4000 open con $8000 baud con t38k4 + inverted main: do serout so\fc, baud, ["hello!", cr] ' send the greeting pause 2500 ' wait 2.5 seconds loop ' repeat forever end demo program (serin_serout2.bs2) ' serin_serout2.bs2 ' using two bs2-ic's, connect the circuit shown in the serin command ' description and run this program on the basic stamp designated as the ' receiver. this program demonstrates the use of flow control (fpin). ' without flow control, the sender would transmit the whole word "hello!" ' in about 1.5 ms. the receiver would catch the first byte at most; by the ' time it got back from the first 1-second pause, the rest of the data ' would be long gone. with flow control, communication is flawless since ' the sender waits for the receiver to catch up. ' {$stamp bs2} ' {$pbasic 2.5} si pin 0 ' serial input fc pin 1 ' flow control pin #select $stamp #case bs2, bs2e, bs2pe t1200 con 813 t2400 con 396 t9600 con 84 t19k2 con 32 t38k4 con 6 note: this example program was written for the bs2 but it can be used with the bs2e, bs2sx, bs2p, bs2pe, and bs2px. this program uses conditional compilation techniques; see chapter 3 for more information. all 2
serin - basic stamp command reference page 414 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com #case bs2sx, bs2p t1200 con 2063 t2400 con 1021 t9600 con 240 t19k2 con 110 t38k4 con 45 #case bs2px t1200 con 3313 t2400 con 1646 t9600 con 396 t19k2 con 188 t38k4 con 84 #endselect inverted con $4000 open con $8000 baud con t38k4 + inverted letter var byte main: do serin si\fc, baud, [letter] ' receive one byte debug letter ' display on screen pause 1000 ' wait one second loop ' repeat forever end
5: basic stamp command reference ? serout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 415 serout bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px serout tpin, baudmode, ( { # } outputdata ) serout tpin { \ fpin } , baudmode, { pace, } { timeout, tlabel, } [ outputdata ] function transmit asynchronous serial data (e.g., rs-232 data).  tpin is a variable/constant/expression (0 ? 16) that specifies the i/o pin through which the serial data wi ll be transmitted. this pin will be set to output mode. on all bs2 models, if tpin is set to 16, the basic stamp uses the dedicated se rial-output pin (sout, physical pin 1), which is normally used by the stamp editor during the download process.  fpin is an optional variable/constant/expression (0 ? 15) that specifies the i/o pin to monitor for flow control status. this pin will be set to input mode. note: fpin must be specified to use the optional timeout and tlabel arguments in the serout command.  baudmode is variable/constant/expression (0 ? 7 on the bs1, 0 ? 65535 on all bs2 models) that specifies serial timing and configuration.  pace is an optional variable/constant/expression (0 ? 65535) that determines the length of the pause between transmitted bytes. note: pace cannot be used simultaneously with timeout and fpin .  timeout is an optional variable/constant/expression (0 ? 65535) that tells serout how long to wait for fpin permission to send. if permission does not arrive in ti me, the program will jump to the address specified by tlabel . note: fpin must be specified to use the optional timeout and tlabel arguments in the serout command.  tlabel is an optional label that must be provided along with timeout. tlabel indicates where the program should go in the event that permission to send data is not gr anted within the period specified by timeout .  outputdata is list of variables, constants, expressions and formatters that tells serout how to format outgoing data. serout can transmit individual or repeating bytes, convert values into decimal, note: expressions are not allowed as arguments on the bs1. the range of the rp in argument on the bs1 is 0 ? 7. note: the bs1's outputdata argument can only be a list of variables and the optional decimal modifier (#). 1 all 2 1 1
serout ? basic stamp command reference page 416 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com hex or binary text representations, or transmit strings of bytes from variable arrays. these actions can be combined in any order in the outputdata list. quick facts bs1 bs2, bs2e bs2sx bs2p bs2pe bs2px units in pace n/a 1 ms 1 ms 1 ms 1 ms 1 ms units in timeout n/a 1 ms 0.4 ms 0.4 ms 1 ms 0.4 ms baud range 300, 600, 1200, and 2400 only 243 to 50k 608 to 115.2k 608 to 115.2k 243 to 50k 972 to 115.2k baud limit with flow control n/a 19.2k 19.2k 19.2k 19.2k 19.2k i/o pins available 0 - 7 0 ? 15 0 - 15 0 ? 15 (in current i/o block) 0 ? 15 (in current i/o block) 0 ? 15 (in current i/o block) other serial port pins n/a sout pin (physical pin 1) when tpin = 16 special cases n/a fpin must be specified to use timeout and tlabel . pace cannot be specified at the same time as timeout. related commands serin serin and debug table 5.104: serout quick facts. explanation one of the most popular forms of communication between electronic devices is serial communication. th ere are two major types of serial communication; asynchronous and synchronous. the serin and serout commands are used to receive and send asynchronous serial data. see the shiftin and shiftout command for information on the synchronous method. the following information is supplemental to what is discussed in the serin command section. please read through the serin command section for additional information. all bs2 models have a line driver on its sout pin ( tpin = 16). the sout pin goes to a pc?s serial data-in pin on the db9 connector built into basic stamp development boards. the connector is wired to allow both programming and run-time serial co mmunication (unless you are using the basic stamp 2 carrier board (#27 120) which is only designed for programming). for the built-in serial port set the tpin argument to 16 in the serout command. s erial communication background . u sing the built - in serial port found on all bs2 models . all 2
5: basic stamp command reference ? serout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 417 all basic stamp models (including the bs1) can also transmit rs-232 data through any of their i/o pins ( tpin = 0 ? 7 for bs1, tpin = 0 ? 15 on all other basic stamp models). the i/o pins only provide a 0 to +5 volt swing (outside of rs-232 specs) and may need to be connected through a line driver for proper operation with all serial ports. most serial ports are able to recognize a 0 to +5 volt swing, however. see figure 5.38 for sample wiring. figure 5.38: serial port diagram showing correct connections to a basic stamp's i/o pin. note: a line driver may have to be used between the i/o pin and the receiving serial port to ensure proper communication. db-9 male (connector side) from i/o pin 2 3 4 transmit data (td) receive data (rd) request to send (rts) 6 7 20 data set ready (dsr) signal ground (sg) data terminal ready (dtr) 3 2 7 6 5 4 db25 function db9 note: the connections shown with double-lines are normally not necessary. they indicate optional connection s to disable hardware handshaking (dtr-dsr-dcd and rts-cts). this is only necessary if you are using softwar e or hardware that expects hardware handshaking. db-25 male (connector side) 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 9 8 7 6 5 4 3 2 1 vss from i/o pin vss 8 data carrier detect (dcd) 1 5 clear to send (cts) 8 figure 5.38 shows the pinouts of the tw o styles of pc serial ports and how to connect them to the basic stamp's i/o pin. though not normally needed, the figure also shows loop back connections that defeat hardware handshaking used by some pc software. note that pc serial ports are always male connectors. the 25-pin style of serial port (called a db25) looks similar to a printer (parallel) po rt except that it is male, whereas a parallel port is female. asynchronous serial communication relies on precise timing. both the sender and receiver must be set for identical timing, usually expressed in bits per second (bps) called baud. serout requires a value called baudmode that tells it the important characteristics of the outgoing serial data; the bit period, number of data and parity bits, and polarity. s erial timing and mode ( baudmode ). 1 a ll 2
serout ? basic stamp command reference page 418 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com on the bs1, serial communication is limited to: no-parity, 8-data bits and 1-stop bit at one of four different speeds: 300, 600, 1200 or 2400 baud. table 5.105 indicates the baudmode value or symbols to use when selecting the desired mode. baudmode value symbol baud rate polarity and output mode 0 t2400 2400 true (always driven) 1 t1200 1200 true (always driven) 2 t600 600 true (always driven) 3 t300 300 true (always driven) 4 n2400 2400 inverted (always driven) 5 n1200 1200 inverted (always driven) 6 n600 600 inverted (always driven) 7 n300 300 inverted (always driven) 8 ot2400 2400 true (open drain, driven high) 9 ot1200 1200 true (open drain, driven high) 10 ot600 600 true (open drain, driven high) 11 ot300 300 true (open drain, driven high) 12 on2400 2400 inverted (open source, driven low) 13 on1200 1200 inverted (open source, driven low) 14 on600 600 inverted (open source, driven low) 15 on300 300 inverted (open source, driven low) table 5.105: bs1 baudmode values. on all bs2 models, serial communication is very flexible. the baudmode argument for serout accepts a 16-bit value that determines its characteristics: 1-stop bit, 8-data bits /no-parity or 7-data bits/even-parity and virtually any speed from as low as 300 baud to greater than 100k baud (depending on the basic st amp model). table 5.106 shows how baudmode is calculated, while table 5.107, table 5.108, and table 5.109 show common baud modes for standard serial baud rates. step 1: determine the bit period (bits 0 ? 11) bs2, bs2e and bs2pe: = int(1,000,000 / baud rate) ? 20 bs2sx and bs2p: = int(2,500,000 / baud rate) ? 20 bs2px: = int(4,000,000 / baud rate) ? 20 note: int means 'convert to integer;' drop the numbers to the right of the decimal point. step 2: set data bits and parity (bit 13) 8-bit/no-parity = 0 7-bit/even-parity = 8192 step 3: select polarity (bit 14) true (noninverted) = 0 inverted = 16384 step 4: select driven or open output (bit 15) driven = 0 open = 32768 table 5.106: baudmode calculation for all bs2 models. add the results of steps 1, 2, 3 and 4 to determine the proper value for the baudmode argument. 1 all 2
5: basic stamp command reference ? serout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 419 table 5.107: bs2, bs2e and bs2pe common baud rates and corresponding baudmodes. baud rate 8-bit no-parity inverted 8-bit no-parity true 7-bit even-parity inverted 7-bit even-parity true 300 19697 3313 27889 11505 600 18030 1646 26222 9838 1200 17197 813 25389 9005 2400 16780 396 24972 8588 4800 16572 188 24764 8380 9600 16468 84 24660 8276 note: for "open" baudmodes used in networking, add 32768 to the values from the table above. if the dedicated serial port ( tpin =16) is used, the data is inverted and driven regardless of the baudmode setting. table 5.108: bs2sx and bs2p common baud rates and corresponding baudmodes. baud rate 8-bit no-parity inverted 8-bit no-parity true 7-bit even-parity inverted 7-bit even-parity true 1200 18447 2063 26639 10255 2400 17405 1021 25597 9213 4800 16884 500 25076 8692 9600 16624 240 24816 8432 note: for "open" baudmodes used in networking, add 32768 to the values from the table above. if the dedicated serial port ( tpin =16) is used, the data is inverted and driven regardless of the baudmode setting. table 5.109: bs2px common baud rates and corresponding baudmodes. baud rate 8-bit no-parity inverted 8-bit no-parity true 7-bit even-parity inverted 7-bit even-parity true 1200 19697 3313 27889 11505 2400 18030 1646 26222 9838 4800 17197 813 25389 9005 9600 16780 396 24792 8588 if you?re communicating with existing software or hardware, its speed(s) and mode(s) will determine your choice of baud rate and mode. see the serin command description for more information. the example below will transmit a single byte through i/o pin 1 at 2400 baud, 8n1, inverted: serout 1, n2400, (65) --or-- serout 1, 16780, [65] c hoosing the proper baud mode . a simple form of serout. 1 all 2 this is written with the bs2's baudmode value. be sure to adjust the value for y our basic stam p model.
serout ? basic stamp command reference page 420 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com here, serout will transmit a byte eq ual to 65 (the ascii value of the character "a") through pin 1. if the basic stamp were connected to a pc running a terminal progra m (set to the same baud rate) the character "a" would appear on the screen (see the ascii character chart in appendix a). what if you really wanted the value 65 to appear on the screen? if you remember from the discussion in the serin command, "it is up to the receiving side (in serial communication) to interpret the values?" in this case, the pc is interpreting the byte-sized value to be the ascii code for the character "a". unless you're also writing the software for the pc, you can't change how the pc interprets the incoming serial data, so to solve this problem, the data needs to be translated before it is sent. the serout command provides a formatter, called the decimal formatter, which will translate the value 65 to two ascii codes for the characters "6" and "5" and then transmit them. look at the following code: serout 1, n2400, (#65) --or-- serout 1, 16780, [dec 65] notice the decimal formatter in the serout command. it is the ?#? (for the bs1) or ?dec? (for all bs2 models) that appears just to the left of the number 65. this tells serout to co nvert the number into separate ascii characters which represent the value in decimal form. if the value 65 in the code were changed to 123, the sero ut command would send three bytes (49, 50 and 51) corresponding to the characters "1", "2" and "3". all bs2 models have many more conversion formatters available for the serout command. see the ?additional conversion formatters? section below for more information. the serout command sends quoted text exactly as it appears in the outputdata list: serout 1, n2400, ("hello" cr) serout 1, n2400, ("num = ", #100) --or-- a simple numeric conversion ; decimal to ascii numeric text . this is written with the bs2's baudmode value. be sure to adjust the value for your basic stamp model. 1 all 2 all 2 1
5: basic stamp command reference ? serout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 421 serout 1, 16780, ["hello", cr] serout 1, 16780, ["num = ", dec 100] the above code will display "hello" on one line and "num = 100" on the next line. notice that you can combine data to output in one serout command, separated by commas. in the example above, we could have written it as one line of code, with "hello", cr, "num = ", dec 100 in the outputdata list. the bs1?s serout command is limited to above-mentioned features. if you are not using a bs1, please continue reading about the additional features below. the serout command can also be configured to pause between transmitted bytes. this is the purpose of the optional pace argument. for example (9600 baud n8, inverted): serout 1, 16780, 1000, ["slowly..."] here, the basic stamp transmits "slowly..." with a 1 second delay between each character. see table 5.104 for units of the pace argument. one good reason to use the pace feature is to support devices that require more than one stop bit. normally, the basic stamp sends data as fast as it can (with a minimum of 1 stop bit between bytes). since a stop bit is really just a resting state in the line (no data transmitted), using the pace option will effectively add multiple st op bits. since the requirement for 2 or more stop bits (on some devices) is really just a "minimum" requirement, the receiving side should receive this data correctly. keep in mind that when we type so mething like ?xyz? into the serout command, the basic stamp actually uses the ascii codes for each of those characters for its tasks. we could also typed: 88, 89, 90 in place of ?xyz? and the program would run the same way since 88 is the ascii code for the ?x? character, 89 is the ascii code for the ?y? character, and so on. the decimal formatter is only one of a whole family of conversion formatters available with serin on al l bs2 models. see table 5.110 for a list of available conversion formatters . all of the conversion formatters work similar to the decimal formatter. the formatters translate the value into separate bytes of data until the en tire number is translated or until the u sing serout' s p ace argument to insert delays between transmitted bytes . u sing ascii codes . a dditional conversion formatters . note: the rest of the code examples for this section are written for the bs2, using the bs2's baudmode and timeout values. be sure to adjust the value for your basic stamp model. this is written with the bs2's baudmode value. be sure to adjust the value for your basic stamp model. all 2 1 all 2
serout ? basic stamp command reference page 422 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com indicated number of digits (in the case of the fixed length formatters) is translated. all bs2 models also have special form atters for outputting a string of characters, and repeated characters. see table 5.111 for a list of these special formatters. conversion formatter type of number notes dec{1..5} decimal, optionally fixed to 1 ? 5 digits 1 sdec{1..5} signed decimal, optionally fixed to 1 ? 5 digits 1,2 hex{1..4} hexadecimal, optionally fixed to 1 ? 4 digits 1,3 shex{1..4} signed hexadecimal, optionally fixed to 1 ? 4 digits 1,2 ihex{1..4} indicated hexadecimal, optionally fixed to 1 ? 4 digits ($ prefix) 1 ishex{1..4} signed, indicated hexadecimal, opti onally fixed to 1 ? 4 digits ($ prefix) 1,2 bin{1..16} binary, optionally fixed to 1 ? 16 digits 1 sbin{1..16} signed binary, optionally fixed to 1 ? 16 digits 1,2 ibin{1..16} indicated binary, optionally fixed to 1 ? 16 digits (% prefix) 1 isbin{1..16} signed, indicated binary, optiona lly fixed to 1 ? 16 digits (% prefix) 1,2 table 5.110: conversion formatters for all bs2 models. 1 fixed-digit formatters like dec4 will pad t he number with leading 0s if necessary; ex: dec4 65 sends 0065. if a number is larg er than the specified number of digits, the leading digits will be dropped; ex: dec4 56422 sends 6422. 2 signed modifiers work under two's complement rules. 3 the hex modifier can be used for bcd to decimal conversion. see ?hex to bcd conversion? on page 97. special formatter action ? displays "symbol = x' + carriage return; where x is a number. default format is decimal, but may be combined with conversion formatters (ex: bin ? x to display "x = binary_number"). asc ? displays "symbol = 'x'" + carriage return; where x is an ascii character. str bytearray {\l} send character string from an arra y. the optional \l argument can be used to limit the output to l characters, otherwise, characters will be sent up to the first byte equal to 0 or the end of ram space is reached. rep byte \l send a string consisting of byte repeated l times (ex: rep "x"\10 sends "xxxxxxxxxx"). table 5.111: special formatters for all bs2 models. the string formatter is useful for transm itting a string of characters from a byte array variable. a string of characters is a set of characters that are arranged or accessed in a certain or der. the characters "abc" could be stored in a string with the "a" first, followed by the "b" and then followed by the "c." a byte array is a similar concept to a string; it contains data that is arranged in a certain order. each of the elements in an array is the t he str ( string ) formatter . all 2
5: basic stamp command reference ? serout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 423 same size. the string "abc" could be stored in a byte array containing three bytes (elements). see the ?defin ing arrays? section in chapter 4 for more information on arrays. here is an example that transmits five bytes (from a byte array) through i/o pin 1 at 9600 bps, n81/inverted: serstr var byte(5) ' create 5-byte array main: serstr(0) = "h" ' fill array serstr(1) = "e" serstr(2) = "l" serstr(3) = "l" serstr(4) = "o" serout 1, 16468, [str serstr\5] ' transmit note that we use the optional \l argument of str. if we didn't specify this, the basic stamp would try to keep sending characters until it found a byte equal to 0. since we didn't specify a last byte of 0 in the array, we chose to tell it explicitly to only send 5 characters. parity is a simple error-checking feature. when the serout command's baudmode is set for even parity it counts the number of 1s in the outgoing byte and uses the parity bit to make th at number even. for instance, if it is sending the 7-bit value: %0011010, it sets the parity bit to 1 in order to make an even number of 1s (four). the receiver also counts the data bi ts to calculate what the parity bit should be. if it matches the parity bi t received, the serial receiver assumes that the data was received correctly. of course, this is not necessarily true, since two incorrectly received bits could make parity seem correct when the data was wrong, or the parity bit itself could be bad when the rest of the data was ok. parity errors are only detected on the receiver side. generally, the receiver determines how to handle the error. in a more robust application, the receiver and tr ansmitter might be set up such that the receiver can request a re-send of da ta that was received with a parity error. when you design an application th at requires serial communication between basic stamp modules, yo u have to work within these limitations: u sing parity and handling parity errors . c ontrolling data flow . all 2
serout ? basic stamp command reference page 424 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com ? when the basic stamp is sending or receiving data, it can?t execute other instructions. ? when the basic stamp is executing other instructions, it can?t send or receive data. the basic stamp does not have a serial buffer as there is in pcs. at most serial rates, the basic stamp cannot receive data via serin, process it, and execute another serin in time to catch the next chunk of data, unless there are significant pauses between data transmissions. these limitations can sometimes be addressed by using flow control; the fpin option for serin and serout (at baud rates of up to the limitation shown in table 5.94). through fpin , serin can tell a basic stamp sender when it is ready to receive data and serout (on the sender) will wait for permission to send. (for that matter, fpin flow control follows the rules of other serial handshaking schemes, but most computers other than the basic stamp cannot start and stop serial transmission on a byte-by-byte basis. that?s why this discussion is limited to communication between basic stamp modules.) here?s an example using flow control on the bs2 (data through i/o pin 1, flow control through i/o pin 0, 9600 baud, n8, noninverted): serdata var byte serout 1\0, 84, [serdata] when serout executes, i/o pin 1 ( tpin ) is made an output, and i/o pin 0 ( fpin ) is made an input, to wait for the ?go? signal from the receiver. here?s the relationship of serial polarity to fpin states. ready to receive ("go") not ready to receive ("stop") inverted fpin is high (1) fpin is low (0) non-inverted fpin is low (0) fpin is high (1) table 5.112: flow control pin states in relation to polarity (inverted or non-inverted) for all bs2 models. see the demo program, below, for a fl ow control example using two bs2s. in the demo program example, withou t flow control, the sender would transmit the whole word ?hello!? in about 6 ms. the receiver would catch the first byte at most; by the time it got back from the first 1-second pause, the rest of the data would be long gone. with flow control, communication is flawless since the sender waits for the receiver to catch up.
5: basic stamp command reference ? serout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 425 in figure 5.39 below, i/o pin 0, fpin , is pulled to ground through a 10k resistor. this is to ensure that the send er sees a stop signal (0 for inverted communications) when the receiver is being programmed. in the flow control examples above, the only way the serout instruction will end (other than reset or power-off) is if the receiver allows it to send the entire outputdata list. if fpin permission never occurs, the program is stuck. however, you can tell the basic stamp to abort serout if it doesn?t receive fpin permission within a specified time period. for instance, to transmit a decimal number through pin 1 at 9600 baud, 8n, inverted and abort serout after 2 seconds (2000 ms) if no fpin permission arrives on i/o pin 0: serout 1\0, 16468, 2000, no_permission, [dec 150] stop no_permission: debug "timeout error", cr if no fpin permission arrives within 2 seconds, the program aborts serout and continues at the label no_permission . figure 5.39: flow-control example circuit. p0 p1 vss bs2 sender p0 p1 bs2 receiver host pc (f or debug) programming cable vss 10k the serout command supports open-drain and open-source output, which makes it possible to network multiple basic stamp modules on a single pair of wires. these "open baudmodes" only actively drive the tpin in one state (for the other state, they si mply disconnect the pin; setting it to an input mode). if two basic stamp modules in a network had their serout lines connected together (while a third device listened on that line) and the basic stamp modules were using always-driven baudmodes, they could simultaneously ou tput two opposite states (i.e.: +5 volts and ground). this would create a short circuit. the heavy current flow would likely damage the i/o pins or the basic stamp modules u sing the serial time - out feature . u sing o pen b audmodes for n etworking basic s tamps . all 2
serout ? basic stamp command reference page 426 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com themselves. since the open baudmodes only drive in one state and float in the other, there's no chance of this kind of short. the polarity selected for serout determines which state is driven and which is open as in table 5.113. state (0) state (1) resistor pulled to inverted open driven gnd (vss) non-inverted driven open +5v (vdd) table 5.113: open baudmode states for all bs2 models. since open baudmodes only drive to one state, they need a resistor to pull the networked line into the other state, as shown in table 5.113 and in figure 5.40 and figure 5.41. open baudmodes allow the basic stamp to share a line, but it is up to your program to resolve other networki ng issues such as who talks when and how to detect, prevent and fix data errors. basic stamp i/o pin gnd (vss) basic stamp i/o pin gnd (vss) to o th er devices to o th er devices 1 k ? vdd figure 5.40: serout open-drain circuit. this circuit is for use with the open, non-inverted baudmode.
5: basic stamp command reference ? serout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 427 figure 5.41: serout open- source circuit. this circuit is for use with the open, inverted baudmode. basic stamp vss i/o pin gnd (vss) basic stamp i/o pin gnd (vss) to o th er devices to o th er devices 1 k ? serial communication, because of its complexity, can be very difficult to work with at times. please follow these guidelines (and those in the "serin troubleshooting" section of the serin command description) when developing a project using the serin and serout commands: 1. always build your project in steps. a. start with small, manageable pieces of code, that deals with serial communication) and test them, one at a time. b. add more and more small pieces, testing them each time, as you go. c. never write a large portion of code that works with serial communication without testing its smallest workable pieces first. 2. pay attention to timing. a. be very careful to calculate an d overestimate the amount of time operations should take within the basic stamp. misunderstanding the timing cons traints is the source of most problems with code that communicate serially. b. if the serial communication in your project is bi-directional, the above statement is even more critical. 3. pay attention to wiring. a. take extra time to study and verify serial communication wiring diagrams. a mistake in wiring can cause strange problems in communication, or no communication at all. make sure to connect the ground pins (vss) between the devices that are commu nicating serially. 4. verify port setting on the pc and in the serin/serout commands. serout t roubleshooting .
serout ? basic stamp command reference page 428 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com a. unmatched settings on the sender and receiver side will cause garbled data transfers or no data transfers. if the data you receive is unreadable, it is most likely a baud rate setting error. 5. if data transmitted to the stamp editor's debug terminal is garbled, verify the output format. a. a common mistake is to send data with serout in ascii format. for example, serout 16, 84, [ 0 ] instead of serout 16, 84, [ dec 0 ]. the first example will send a byte equal to 0 to the pc, resulting in the debug terminal clearing the screen (since 0 is the control character for a clear-screen action). demo program (serout.bs1) ' serout.bs1 ' this program transmits the string "abcd" followed by a number and a ' carriage-return at 2400 baud, inverted, n81 format. ' {$stamp bs1} ' {$pbasic 1.0} symbol sout = 1 symbol baud = n2400 symbol value = w1 setup: value = 1 main: serout sout, baud, ("abcd", #value) value = value + 1 pause 250 goto main end demo program (serin_serout1.bs2) ' serin_serout1.bs2 ' using two bs2-ic's, connect the circuit shown in the serin command ' description and run this program on the basic stamp designated as the ' sender. this program demonstrates the use of flow control (fpin). ' without flow control, the sender would transmit the whole word "hello!" ' in about 1.5 ms. the receiver would catch the first byte at most; by the ' time it got back from the first 1-second pause, the rest of the data note: this example program was written for bs2?s but it can be used with the bs2e, bs2sx, bs2p, bs2pe, and bs2px. this program uses conditional compilation techniques; see chapter 3 for more information. all 2 1
5: basic stamp command reference ? serout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 429 ' would be long gone. with flow control, communication is flawless since ' the sender waits for the receiver to catch up. ' {$stamp bs2} ' {$pbasic 2.5} so pin 1 ' serial output fc pin 0 ' flow control pin #select $stamp #case bs2, bs2e, bs2pe t1200 con 813 t2400 con 396 t9600 con 84 t19k2 con 32 t38k4 con 6 #case bs2sx, bs2p t1200 con 2063 t2400 con 1021 t9600 con 240 t19k2 con 110 t38k4 con 45 #case bs2px t1200 con 3313 t2400 con 1646 t9600 con 396 t19k2 con 188 t38k4 con 84 #endselect inverted con $4000 open con $8000 baud con t38k4 + inverted main: do serout so\fc, baud, ["hello!", cr] ' send the greeting pause 2500 ' wait 2.5 seconds loop ' repeat forever end demo program (serin_serout2.bs2) ' serin_serout2.bs2 ' using two bs2-ic's, connect the circuit shown in the serin command ' description and run this program on the basic stamp designated as the ' receiver. this program demonstrates the use of flow control (fpin). ' without flow control, the sender would transmit the whole word "hello!" ' in about 1.5 ms. the receiver would catch the first byte at most; by the ' time it got back from the first 1-second pause, the rest of the data ' would be long gone. with flow control, communication is flawless since note: this example program was written for bs2?s but it can be used with the bs2e, bs2sx, bs2p, bs2pe, and bs2px . this program uses conditional compilation techniques; see chapter 3 for more information. all 2
serout ? basic stamp command reference page 430 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com ' the sender waits for the receiver to catch up. ' {$stamp bs2} ' {$pbasic 2.5} si pin 0 ' serial input fc pin 1 ' flow control pin #select $stamp #case bs2, bs2e, bs2pe t1200 con 813 t2400 con 396 t9600 con 84 t19k2 con 32 t38k4 con 6 #case bs2sx, bs2p t1200 con 2063 t2400 con 1021 t9600 con 240 t19k2 con 110 t38k4 con 45 #case bs2px t1200 con 3313 t2400 con 1646 t9600 con 396 t19k2 con 188 t38k4 con 84 #endselect inverted con $4000 open con $8000 baud con t38k4 + inverted letter var byte main: do serin si\fc, baud, [letter] ' recieve one byte debug letter ' display on screen pause 1000 ' wait one second loop ' repeat forever end
5: basic stamp command reference ? shiftin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 431 shiftin bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px shiftin dpin, cpin, mode, [ variable { \ bits } { , variable { \ bits } ? } ] function shift data in from a synchronous serial device.  dpin is a variable/constant/expression (0 ? 15) that specifies the i/o pin that will be connected to the synchronous serial device?s data output. this pin will be set to input mode.  cpin is a variable/constant/expression (0 ? 15) that specifies the i/o pin that will be connected to the synchronous serial device?s clock input. this pin will be set to output mode.  mode is a variable/constant/expression (0 ? 3), or one of four predefined symbols, that tells shiftin the order in which data bits are to be arranged and the relationsh ip of clock pulses to valid data. see table 5.115 for value and symbol definitions.  variable is a variable in which incoming data bits will be stored.  bits is an optional variable/constant/expression (1 ? 16) specifying how many bits are to be input by shiftin. if no bits argument is given, shiftin defaults to 8 bits. quick facts table 5.114: shiftin quick facts. bs2/bs2e bs2sx/bs2p bs2pe bs2px timing of t h and t l 14 s / 46 s 5.6 s / 18 s 14 s / 46 s 3.6 s / 11.8 s transmission rate ~16 kbits/sec. ~42 kbits/sec. ~16 kbits/sec. ~ 65 kbits/sec. related command shiftout explanation shiftin and shiftout provide an easy method of acquiring data from synchronous serial devices. synchron ous serial differs from asynchronous serial (like serin and serout) in that the timing of data bits (on a data line) is specified in relationship to clock pulses (on a clock line). data bits may be valid after the rising or falling edge of the clock line. this kind of serial protocol is called synchronou s peripheral interface (spi) and is commonly used by controller periph erals like adcs, dacs, clocks, memory devices, etc. all 2
shiftin ? basic stamp command reference page 432 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com at their heart, synchronous-serial devices are essentially shift-registers; trains of flip-flops that pass data bits along in a bucket brigade fashion to a single data output pin. another bit is output each time the appropriate edge (rising or falling, depending on the device) appears on the clock line. the shiftin instruction first causes the clock pin to output low and the data pin to switch to input mode. then, shiftin either reads the data pin and generates a clock pulse (pre mode) or generates a clock pulse then reads the data pin (post mode). shiftin continues to generate clock pulses and read the data pin for as many data bits as are required. making shiftin work with a particular device is a matter of matching the mode and number of bits to that de vice?s protocol. most manufacturers use a timing diagram to illustrate the relationship of clock and data. items to look for include: 1) which bit of the data arrives first; most significant bit (msb) or least significant bit (lsb) and 2) is the first data bit ready before the first clock pulse (pre) or after the first clock pulse (post). table 5.115 shows the values and symbols available for mode, and figure 5.42 shows shiftin?s timing. symbol value meaning msbpre 0 data is msb-first; sample bits before clock pulse lsbpre 1 data is lsb-first; sample bits before clock pulse msbpost 2 data is msb-first; sample bits after clock pulse lsbpost 3 data is lsb-first; sample bits after clock pulse table 5.115: shiftin mode values and symbols. (msb is most-significant bit; the highest or leftm ost bit of a nibble, byte, or word. lsb is the least-significant bit; the lo west or rightmost bit of a nibble, byte, or word.) figure 5.42: shiftin timing diagram. refer to the shiftin quick facts table for timing information on t h (t high) and t l (t low). t h cloc k (cpin) data (dpin) - t l - -pre modes sample data before clock pulse 1st -post modes sample data before clock pulse 2nd shiftin operation .
5: basic stamp command reference ? shiftin basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 433 here is a simple example: result var byte shiftin 0, 1, msbpre, [result] here, the shiftin command will read i/o pin 0 ( dpin ) and will generate a clock signal on i/o 1 ( cpin ). the data that arrives on dpin depends on the device connected to it. let's say, for example, that a shift register is connected and has a value of $af (10101111) waiting to be sent. additionally, let's assume that the shift register sends out the most significant bit first, an d the first bit is on dpin before the first clock pulse (msbpre). the shiftin command above will generate eight clock pulses and sample the data pin ( dpin ) eight times. afterward, the result variable will contain the value $af. by default, shiftin acquires eight bi ts, but you can set it to shift any number of bits from 1 to 16 with the bits argument. for example: result var byte shiftin 0, 1, msbpre, [result\4] will only input the first 4 bits. in the example discussed above, the result variable will be left with %1010. some devices return more than 16 bits. for example, most 8-bit shift registers can be daisy-chained together to form any multiple of 8 bits; 16, 24, 32, 40... to solve this, you can us e a single shiftin instruction with multiple variables. each variable can be assigned a particular number of bits with the bits argument. as in: resultlo var word resulthi var nib shiftin 0, 1, msbpre, [resulthi\4, resultlo\16] the above code will first shift in four bits into resulthi and then 16 bits into resultlo . the two variables together make up a 20 bit value. a simple shiftin example . c ontrolling the number of bits received .
shiftin ? basic stamp command reference page 434 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com demo program (shiftin.bs2) ' shiftin.bs2 ' this program uses the shiftin instruction to interface with the adc0831 ' 8-bit analog-to-digital converter from national semiconductor. ' {$stamp bs2} ' {$pbasic 2.5} cs pin 0 ' chip select adata pin 1 ' data pin clk pin 2 ' clock pin adcres var byte ' adc result setup: high cs ' deselect adc ' in the loop below, just three lines of code are required to read the ' adc0831. the shiftin command does most of the work. the mode argument in ' the shiftin command specifies msb or lsb-first and whether to sample data ' before or after the clock. in this case, we chose msb-first, post-clock. ' the adc0831 precedes its data output with a dummy bit, which we take care ' of by specifying 9 bits of data instead of 8. main: do low cs ' activate the adc0831 shiftin adata, clk, msbpost, [adcres\9] ' shift in the data high cs ' deactivate adc0831 debug ? adcres ' show conversion result pause 1000 ' wait one second loop ' repeat end all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? shiftout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 435 shiftout bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px shiftout dpin, cpin, mode, [ outputdata { \ bits } { ,outputdata { \ bits } ? } ] function shift data out to a synchronous serial device.  dpin is a variable/constant/expression (0 ? 15) that specifies the i/o pin that will be connected to the synchronous serial device?s data input. this pin will be set to output mode.  cpin is a variable/constant/expression (0 ? 15) that specifies the i/o pin that will be connected to the synchronous serial device?s clock input. this pin will be set to output mode.  mode is a variable/constant/expression (0 ? 1), or one of two predefined symbols, that tells shiftout the order in which data bits are to be arranged. see table 5.117 for value and symbol definitions.  outputdata is a variable/constant/expression containing the data to be sent.  bits is an optional variable/constant/expression (1 ? 16) specifying how many bits are to be output by shiftout. when the bits argument is given, the basic stamp transmits the rightmost number of bits specifed, regardless of the mode . if no bits argument is given, shiftout defaults to 8 bits. quick facts table 5.116: shiftout quick facts. bs2, bs2e bs2sx, bs2p bs2pe bs2px timing of t h and t l , 14 s / 46 s 5.6 s / 18 s 14 s / 46 s 3.6 s / 11.8 s timing of t a and t b 15 s / 30 s 6.3 s / 12.5 s 15 s / 30 s 4 s / 7.8 s transmission rate ~16 kbits/sec. ~42 kbits/sec. ~16 kbits/sec. ~65 kbits/sec. related command shiftout explanation shiftin and shiftout provide an easy method of acquiring data from synchronous serial devices. synchronous serial differs from asynchronous serial (like serin and serout) in that the timing of data bits (on a data line) is specified in relationship to clock pulses (on a clock line). data bits may be valid after the rising or falling edge of the clock line. this kind of all 2
shiftout ? basic stamp command reference page 436 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com serial protocol is commonly called sy nchronous peripheral interface (spi) and is used by controller peripherals like adcs, dacs, clocks, memory devices, etc. at their heart, synchronous-serial devices are essentially shift-registers; trains of flip-flops that receive data bi ts in a bucket brigade fashion from a single data input pin. an other bit is input each time the appropriate edge (rising or falling, depending on the device) appears on the clock line. the shiftout instruction first causes the clock pin to output low and the data pin to switch to output mode. then, shiftout sets the data pin to the next bit state to be output an d generates a clock pulse. shiftout continues to generate clock pulses and places the next data bit on the data pin for as many data bits as are required for transmission. making shiftout work with a particular device is a matter of matching the mode and number of bits to that device?s protocol. most manufacturers use a timing diagram to illustrate the relationship of clock and data. one of the most important items to look for is which bit of the data should be transmitted first; most significant bit (msb) or least significant bit (lsb). table 5.117 shows the values and symbols available for mode and figure 5.43 shows shiftout?s timing. symbol value meaning lsbfirst 0 data is shifted out lsb-first msbfirst 1 data is shifted out msb-first table 5.117: shiftout mode values and symbols. (msb is most-significant bit; the highest or leftm ost bit of a nibble, byte, or word. lsb is the least-significant bit; the lo west or rightmost bit of a nibble, byte, or word.) t h cloc k (cpin) data (dpin) t l shiftout begins, makes cpin output low =previous state of pin unknown t a t a t b figure 5.43: shiftout timing diagram. refer to the shiftout quick facts table for timing information on t h , t l , t a and t b . shiftout operation .
5: basic stamp command reference ? shiftout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 437 here is a simple example: shiftout 0, 1, msbfirst, [250] here, the shiftout command will write to i/o pin 0 ( dpin ) and will generate a clock signal on i/o pin 1 ( cpin ). the shiftout command will generate eight clock pulses while writ ing each bit (of the 8-bit value 250) onto the data pin ( dpin ). in this case, it will start with the most significant bit first as indicated by the mode value of msbfirst. by default, shiftout transmits eight bits, but you can set it to shift any number of bits from 1 to 16 with the bits argument. for example: shiftout 0, 1, msbfirst, [250\4] will output only the lowest (rightmost) four bits (%1010 in this case). but what if you want to output the leftmost bits of a given value? by adding the right-shift operator (>>) to the code you can adjust the output as required: shiftout 0, 1, msbfirst, [(250 >> 2)\6] will output the upper six bits (%111110 in this case). some devices require more than 16 bits . to solve this, you can use a single shiftout command with multiple values. each value can be assigned a particular number of bits with the bits argument. as in: shiftout 0, 1, msbfirst, [250\4, 1045\16] the above code will first shift out four bits of the number 250 (%1010) and then 16 bits of the number 1045 (%0000010000010101). the two values together make up a 20 bit value. in the examples above, specific numbers were entered as the data to transmit, but, of course, the shifto ut command will accept variables and expressions for the outputdata and even for the bits argument. a simple shiftout example . c ontrolling the number of bits transmitted . shiftout accepts variables and expressions for o utput d ata and b its arguments .
shiftout ? basic stamp command reference page 438 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com 74hc595 to p 0 1 2 3 4 5 6 7 8 16 15 14 13 12 11 10 9 qb qc qd qe qf qg qh gnd vcc qa data in oe latch clk reset sqh vss leds 470 (all) ? vdd vdd vss to p 2 to p 1 figure 5.44: circuit for demo program shiftout.bs2. demo program (shiftout.bs2) ' shiftout.bs2 ' this program uses the shiftout command to interface to the 74hc595 shift ' register as an 8-bit output port. the '595 requires a minimum of three ' inputs: data, clock, and latch. see the figure in the shiftout command ' description in the manual for wiring information. shiftout automatically ' handles the data and clock, pulsing the clock to shift data bits into the ' '595. an extra step (pulsing the latch input) is required to move the ' shifted bits in parallel onto the '595's output pins. note: this code ' does not control the output-enable or reset lines of the '595. this means ' that before the basic stamp first sends, the '595's output latches are ' turned on and may contain random data. in critical applications, you ' should hold output-enable high (disabled) until the basic stamp can take ' control. ' {$stamp bs2} ' {$pbasic 2.5} dpin pin 0 ' data pin to 74hc595 clk pin 1 ' shift clock to 74hc595 latch pin 2 ' latch 74hc595 outputs counter var byte setup: low latch ' initialize latch output ' this loop moves the 8-bit value 'counter' onto the output lines of the ' '595, pauses, then increments counter and repeats. the data is shifted note: this example program can be used with all bs2 models by changing the $stamp directive accordingly. all 2
5: basic stamp command reference ? shiftout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 439 ' msb first so that the msb appears on pin qh and the lsb on qa. changing ' msbfirst to lsbfirst causes the data to appear backwards on the outputs. main: do shiftout dpin, clk, msbfirst, [counter] ' send the bits pulsout latch, 1 ' transfer to outputs pause 100 ' wait 0.1 seconds counter = counter + 1 ' increment counter loop end
shiftout ? basic stamp command reference page 440 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? sleep basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 441 sleep bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px sleep duration function put the basic stamp into low-power mode for a specified time .  duration is a variable/constant/expression (1 ? 65535) that specifies the duration of sleep. the unit of time for duration is 1 second, though the basic stamp rounds up to the nearest multiple of 2.3 seconds. quick facts table 5.118: sleep quick facts. note: current measurements are based on 5-volt power, no extra loads and 75 f ambient temperature. bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px current draw during run 1 ma 3 ma 25 ma 60 ma 40 ma 15 ma 55 ma current draw during sleep 25 a 50 a 200 a 500 a 350 a 36 a 450 a related commands end and nap end, nap and pollwait accuracy of sleep 1% @ 75 f with stable power supply explanation sleep allows the basic stamp to turn it self off, then turn back on after a programmed period of time. the leng th of sleep can range from 2.3 seconds to slightly over 18 hours. power consumption is reduced to the amount described in table 5.118, assuming no loads are being driven. the resolution of the sleep instruction is 2.304 seconds. sleep rounds the specified number of seconds up to the nearest multiple of 2.304. for example, sleep 1 causes 2.304 second s of sleep, while sleep 10 causes 11.52 seconds (5 x 2.304) of sleep. pins retain their previous i/o direct ions during sleep. however, outputs are interrupted every 2.3 seconds during sleep due to the way the chip keeps time. the alarm clock that wakes the basic stamp up is called the watchdog timer. the watchdog is a resi stor/capacitor oscillator built into the interpreter chip. during sleep, the chip periodically wakes up and adjusts a counter to determine how long it has been asleep. if it isn?t time to wake up, the chip ?hits the snooze bar? and goes back to sleep. note: expressions are not allowed as arguments on the bs1. 1 a ll 2 1
sleep ? basic stamp command reference page 442 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com to ensure accuracy of sleep intervals, the basic stamp periodically compares the watchdog timer to the mo re-accurate resonator time base. it calculates a correction factor that it us es during sleep. as a result, longer sleep intervals are accurate to approximately 1 percent. if your application is driving loads (sourcing or sinking current through output-high or output-low pins) during sleep, current will be interrupted for about 18 ms (60 s on the bs2pe) when the basic stamp wakes up every 2.3 seconds. the reason is th at the watchdog-timer reset that awakens the basic stamp also causes all of the pins to switch to input mode for approximately 18 ms. when the interpreter firmware regains control of the processor, it restores the i/o directions dictated by your program. if you plan to use end, nap, pollwait or sleep in your programs, make sure that your loads can tolera te these periodic power outages. the simplest solution is often to connect resistors high or low (to +5v or ground) as appropriate to ensure a continuing supply of current during the reset glitch. the demo program demonstrates the effects of this glitch. figure 5.45: sleep example led circuit. demo program (sleep.bs2) ' sleep.bs2 ' this program lights an led and then goes to sleep. connect an led to pin ' 0 as shown in the description of sleep in the manual and run the program. ' the led will turn on, then the basic stamp will go to sleep. during ' sleep,the led will remain on, but will blink at intervals of ' approximately 2.3 seconds due to the watchdog timeout and reset. ' {$stamp bs2} setup: low 0 ' turn led on note: this example program is written for the bs2, but it also can be used with the bs1 and all other bs2 models by changing the $stamp directive accordingly. 1 a ll 2
5: basic stamp command reference ? sleep basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 443 snooze: sleep 10 ' sleep for 10 seconds goto snooze end
sleep ? basic stamp command reference page 444 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? sound basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 445 sound bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px sound pin, ( note, duration { , note, duration?} ) (see freqout) function generate square-wave tones for a specified period.  pin is a variable/constant (0 ? 7) that specifies the i/o pin to use. this pin will be set to output mode.  note is a variable/constant (0 ? 255) specifying the type and frequency of the tone. 1 ? 127 are ascending tones and 128 ? 255 are ascending white noises ranging from buzzing (128) to hissing (255).  duration is a variable/constant (1 - 255) specifying the amount of time to generate the tone(s ). the unit of time for duration is 12 ms. quick facts table 5.119: sound quick facts. bs1 units in duration 12 ms available sounds 256 frequency range 94.8 hz to 10,550 hz explanation sound generates one of 256 square-wave frequencies on an i/o pin. the output pin should be connecte d as shown in figure 5.46. the tones produced by sound can vary in frequency from 94.8 hz (1) to 10,550 hz (127). if you need to determine the frequency corresponding to a given note value, or need to find the note value that will give you best approximation for a given frequency, use the equations below. note = 127 ? ( ((1/frequency)-0.000095)/0.000083 ) --and-- frequency = ( 1/(0.000095 + ((127?note)*0.000083) ) in the above equations, frequency is in hertz (hz). all 2 1
sound ? basic stamp command reference page 446 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com from i/o pin 1k 0.1 f0.01 f 1k driving an audio amplifier amplifier (e .g., radio shack 277-1008c) vss vss vss 10 f (both) + + 40 ? speaker (or 8 ? in series with 33 ? resistor) from i/o pin c1 c2 notes: c1 may be omitted for piezo speakers c2 is optional, but reduces high-frequency noise driving a speaker vss vss figure 5.46: example rc filter circuits for driving an audio amplifier ( top ) or a speaker( bottom ). demo program (sound.bs1) ' sound.bs1 ' this program generates a constant tone 25 followed by an ascending tones. ' both the tones have the same duration. ' {$stamp bs1} ' {$pbasic 1.0} symbol tone = b2 main: for tone = 0 to 255 sound 0, (25, 10, tone, 10) next end 1
5: basic stamp command reference ? stop basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 447 stop bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px stop function stop program execution. quick facts table 5.120: stop quick facts. all bs2 models related command end explanation stop prevents the basic stamp from executing any further instructions until it is reset. the following actions will reset the basic stamp: 1. pressing and releasing the reset button on the development board. 2. driving the res pin low then letting it float (high). 3. downloading a new program 4. disconnecting then reconnecting the power. stop differs from end in two respects: 1. stop does not put the basic st amp into low-power mode. the basic stamp draws just as much current as if it were actively running program instructions. 2. the output glitch that occurs af ter a program has "ended" does not occur after a program has "stopped." demo program (stop.bs2) ' stop.bs2 ' this program is similar to sleep.bs2 except that the led will not blink ' since the basic stamp does not go into low power mode. use the circuit ' shown in the description of the sleep command for this example. ' {$stamp bs2} ' {$pbasic 2.5} main: low 0 ' turn led on stop ' stop program all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly. all 2
stop ? basic stamp command reference page 448 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? store basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 449 store bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px store programslot function designate a program slot for the read/write instructions to operate upon.  programslot is a variable/constant/expression (0 ? 7 on bs2p and bs2px, 0-15 on bs2pe) that specifies the program slot to use for read and write instructions. quick facts table 5.121: store quick facts. bs2p and bs2px bs2pe program slot range 0 ?7 0 ?15 related commands read and write explanation store tells the bs2p, bs2p e, and bs2px which program slot to use when a read or write instruction is executed. the store command only affects the read and write instructions. the store command allows a progra m to access all eeprom locations that exist on the bs2p, bs2pe, and bs2px regardless of which program is running. the read and write commands can only access locations 0 to 2047 within a single program slot. the store command switches the program slot that the read and write commands operate on. the default program slot that the read and write instructions operate on is that of the currently running program. the store command can be used to temporarily change this, to any program slot. the change will remain in effect until another store command is issued, or until another program slot is executed.
store ? basic stamp command reference page 450 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com demo program (store0.bsp) ' store0.bsp ' this program demonstrates the store command and how it affects the read ' and write commands. this program "store0.bsp" is intended to be down- ' loaded into program slot 0. it is meant to work with store1.bsp and ' store2.bsp. each program is very similar (they display the current ' program slot and read/write slot numbers and the values contained in the ' first five eeprom locations. each program slot will have different data ' due to different data commands in each of the programs downloaded. ' {$stamp bs2p, store1.bsp, store2.bsp} ' {$pbasic 2.5} #if ($stamp < bs2p) #then #error "this program requires bs2p, bs2pe, or bs2px." #endif idx var word ' index value var byte localdata data @0, 1, 2, 3, 4, 5 main: gosub show_slot_info ' show slot info/data pause 2000 store 1 ' point read/write to slot 1 gosub show_slot_info pause 2000 run 1 ' run program in slot 1 end show_slot_info: get 127, value debug cr, "pgm slot: ", dec value.nib0, cr, "r/w slot: ", dec value.nib1, cr, cr for idx = 0 to 4 read idx, value debug "location: ", dec idx, tab, "value: ", dec3 value, cr next return note: this example program can be used with the bs2p, bs2pe, and bs2px. this program uses conditional compilation techniques; see chapter 3 for more information.
5: basic stamp command reference ? store basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 451 demo program (store1.bsp) ' store1.bsp ' {$stamp bs2p} ' {$pbasic 2.5} idx var word ' index value var byte localdata data @0, 6, 7, 8, 9, 10 main: gosub show_slot_info ' show slot info/data pause 2000 store 0 ' point read/write to slot 0 gosub show_slot_info pause 2000 run 2 ' run program in slot 2 end show_slot_info: get 127, value debug cr, "pgm slot: ", dec value.nib0, cr, "r/w slot: ", dec value.nib1, cr, cr for idx = 0 to 4 read idx, value debug "location: ", dec idx, tab, "value: ", dec3 value, cr next return demo program (store2.bsp) ' store2.bsp ' {$stamp bs2p} ' {$pbasic 2.5} idx var word ' index value var byte localdata data @0, 11, 12, 13, 14, 15 main: gosub show_slot_info ' show slot info/data pause 2000 store 0 ' point read/write to slot 0 note: this example program can be used with the bs2p, bs2pe, and bs2px by changing the $stamp directive accordingly. note: this example program can be used with the bs2p, bs2pe, and bs2px by changing the $stamp directive accordingly.
store ? basic stamp command reference page 452 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com gosub show_slot_info end show_slot_info: get 127, value debug cr, "pgm slot: ", dec value.nib0, cr, "r/w slot: ", dec value.nib1, cr, cr for idx = 0 to 4 read idx, value debug "location: ", dec idx, tab, "value: ", dec3 value, cr next return the next demo program, storeall.bsp, is not related to the previous three programs. storeall.bsp demonstrates the use of the store command to treat contiguous program slots as one block of memory (14 kbytes on the bs2p and bs2px, 30 kbyt es on the bs2pe). this illustrates one of the most powerful uses of the store command. demo program (storeall.bsp) ' storeall.bsp ' this program demonstrates the store command and how it can be used to ' "flatten" the eeprom space for applications requiring a lot of storage. ' this program writes to eeprom locations within program slots 1 though 7 ' on the bs2p and bs2px, and 1 through 15 on the bs2pe, thus, has access to ' 14- or 30-kbytes of space. ' {$stamp bs2p} ' {$pbasic 2.5} #select $stamp #case bs2, bs2e, bs2sx #error "this program requires bs2p, bs2pe, or bs2px." #case bs2p, bs2px hislot con 7 #case bs2pe hislot con 15 #endselect loslot con 1 ' first slot for "flat" ee memsize con hislot - loslot + 1 * 2048 eeaddr var word ' address pointer value var word ' cell value slot var byte ' current r/w slot note: this example program can be used with the bs2p, bs2pe, and bs2px. this program uses conditional compilation techniques; see chapter 3 for more information.
5: basic stamp command reference ? store basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 453 main: debug "flat memory", cr, "---------------------", cr, "first slot..... ", dec loslot, cr, "last slot...... ", dec hislot, cr, "flat ee size... ", dec memsize, cr, cr pause 2000 debug "writing to flat memory...", cr pause 1000 for eeaddr = 0 to (memsize - 1) step 128 ' step through "flat" ee value = eeaddr * 2 ' generate value gosub write_word ' write it get 127, slot ' get r/w slot debug "--> location: ", dec5 eeaddr, " ", ' show "flat" address "value: ", dec5 value, " ", ' show value "(", dec slot.nib1, ")", cr ' show slot next debug cr debug "reading from flat memory...", cr pause 1000 for eeaddr = 0 to (memsize - 1) step 128 gosub read_word ' read value from ee get 127, slot ' get w/r slot debug "<-- location: ", dec5 eeaddr, " ", "value: ", dec5 value, " ", "(", dec slot.nib1, ") " if (value <> (2 * eeaddr)) then ' verify location debug "- error" endif debug cr next end write_word: ' note: only use even-byte eeaddr with this routine store (eeaddr >> 11) + loslot ' set slot write eeaddr, word value ' write value return read_word: ' note: only use even-byte eeaddr with this routine store (eeaddr >> 11) + loslot ' set slot read eeaddr, word value ' read value return
store ? basic stamp command reference page 454 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? toggle basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 455 toggle bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px toggle pin function invert the state of an output pin.  pin is a variable/constant/expression (0 ? 15) that specifies which i/o pin to switch logic state. this pin will be placed into output mode. quick facts table 5.122: toggle quick facts. bs1 all bs2 models affected register pins outs related commands high and low explanation toggle sets a pin to output mode and inverts the output state of the pin, changing 0 to 1 and 1 to 0. in some situations toggle may appear to have no effect on a pin?s state. for example, suppose pin 2 is in input mode and pulled to +5v by a 10k resistor. then the following code executes: dir2 = 0 ' make p2 an input pin2 = 0 ' make p2 output driver low debug pin2 ' show p2 state (1 due to pull-up) toggle 2 ' toggle p2 debug pin2 ' show p2 state (1 again) - or - dir2 = 0 ' make p2 an input out2 = 0 ' make p2 output driver low debug ? in2 ' show p2 state (1 due to pull-up) toggle 2 ' toggle p2 debug ? in2 ' show p2 state (1 again) the state of pin 2 doesn?t change; it's high (due to the resistor) before toggle, and it?s high (due to the pi n being output high) afterward. the point is that toggle works on the outs register (pins on the bs1), which may not match the pin?s state when the pin is initially an input. to note: expressions are not allowed as arguments on the bs1. the range of the pin argument on the bs1 is 0 ? 7. 1 a ll 2 1 1 all 2
toggle ? basic stamp command reference page 456 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com guarantee that the state actually changes, regardless of the initial input or output mode, do this: pin2 = pin2 ' make output driver match input toggle 2 ' then toggle - or - out2 = in2 ' make output driver match input toggle 2 ' then toggle figure 5.47: example led circuit for toggle demo programs. demo program (toggle.bs1) ' toggle.bs1 ' connect leds to pins 0 through 3 as shown in the toggle command descrip- ' tion in the manual and run this program. the toggle command will treat ' you to a light show. you may also run the demo without leds. the debug ' window will show you the states of pins 0 through 3. ' {$stamp bs1} ' {$pbasic 1.0} symbol thepin = b0 ' pin 0 - 3 setup: dirs = %1111 ' make leds output, low main: for thepin = 0 to 3 ' loop through pins toggle thepin ' toggle current pin debug cls, %pins ' show on debug pause 100 ' short delay next goto main ' repeat forever end all 2 1 1
5: basic stamp command reference ? toggle basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 457 demo program (toggle.bs2) ' toggle.bs2 ' connect leds to pins 0 through 3 as shown in the toggle command descrip- ' tion in the manual and run this program. the toggle command will treat ' you to a light show. you may also run the demo without leds. the debug ' window will show you the states of pins 0 through 3. ' {$stamp bs2} ' {$pbasic 2.5} thepin var nib ' pin 0 - 3 setup: dira = %1111 ' make leds output, low main: do for thepin = 0 to 3 ' loop through pins toggle thepin ' toggle current pin debug home, bin4 outa ' show on debug pause 250 ' short delay next loop ' repeat forever end all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
toggle ? basic stamp command reference page 458 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? write basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 459 write bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px write location, value write location, { word } value { , { word } value... } function write value into location in eeprom.  location is a variable/constant/expression (0 ? 255 on bs1, 0 ? 2047 on all bs2 models) that specifies the eeprom address to write to.  value is a variable/constant/expression (0 ? 255, or 0 ? 65535 if using the optional word modifier) to store in the eeprom. quick facts table 5.123: write quick facts. bs1 bs2 bs2e and bs2sx bs2p, bs2pe, bs2px range of eeprom locations 0 to 255 0 to 2047 0 to 2047 0 to 2047 (see notes below) maximum number of writes per location 10 million 10 million 100,000 100,000 special notes n/a n/a write only works with current program slot on bs2e and bs2sx. write works with an y program slot as set b y t he store command. related commands read and eeprom read and data read and data read, data, and store pbasic 2.5 syntax options n/a multiple sequential variables may be written to the scratch pad ram, and the optional word modifier may be specified to store 16-bit values. explanation the eeprom is used for both progra m storage (which builds downward from address 255 on bs1, 2047 on a ll bs2 models) and data storage (which builds upward from address 0). the write instruction stores a value to any eeprom address. any location within the eeprom can be written to (including your pbasic program's lo cations) at run-time . this feature is mainly used to store long-term data to eeprom; data stored in eeprom is not lost when the power is removed. note: expressions are not allowed as arguments on the bs1. 1 all 2 1 note: optional arguments require pbasic 2.5.
write ? basic stamp command reference page 460 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the following write command stores the value 245 at location 100: write 100, 245 --or-- write 100, 245 the eeprom is organized as a sequential set of byte-sized memory locations. the write command normally only stores byte-sized values into eeprom. this does not mean th at you can't write word-sized values, however. a word consists of two bytes, called a low-byte and a high-byte. if you wanted to write a word-sized value, you'll need to use two write commands and a word-sized value or variable. for example, symbol value = w0 symbol vallo = b0 symbol valhi = b1 value = 1125 write 0, vallo ' write low byte write 1, valhi ' write high byte - or - value var word value = 1125 write 0, value.lowbyte ' write low byte write 1, value.highbyte ' write high byte when this program runs, the two write commands will store the low- byte and high-byte of the number 1125 into eeprom. on all bs2 models, with pbasic 2.5 you can use a single write command with the word modifier to wr ite a 16-bit value. the low-byte of the value will be written to location , the high byte will be written to location + 1. w riting word values vs . byte values . a simple write command . 1 all 2 1 note: this method is required only if using pbasic 2.0. see section below for pbasic 2.5 method. all 2
5: basic stamp command reference ? write basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 461 ' {$pbasic 2.5} value var word value = 1125 write 0, word value ' write two bytes when using pbasic 2.5, a single write command can write multiple bytes and words to sequential eep rom locations. for example: ' {$pbasic 2.5} value var byte value2 var word value = 18 value2 = 1125 write 25, value, word value2 ' write byte to location 25 ' and word to locations 26 and 27 eeprom differs from ram, the memory in which variables are stored, in several respects: 1. writing to eeprom takes more ti me than storing a value in a variable. depending on many factors, it may take several milliseconds for the eeprom to complete a write. ram storage is nearly instantaneous. 2. the eeprom can only accept a finite number of write cycles per location before it wears out. table 5.123 indicates the guaranteed number of writes before failure. if a program frequently writes to the same eeprom location, it makes sense to estimate how long it might take to exceed the guaranteed maximum. for example, on the bs2, at one write per second (86,400 writes/day) it would take nearly 116 days of continuous operation to exceed 10 million. 3. the primary function of the eeprom is to store programs (data is stored in leftover space). if data overwrites a portion of your program, the program will most likely crash. check the program?s memory map to determine what portion of memory your program occupies and make sure that eeprom writes cannot stray into this area. you may also use the data directive on all bs2 models to set aside eeprom space. s pecial notes for eeprom usage . all 2 all 2
write ? basic stamp command reference page 462 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com on the bs1, location 255 holds the address of the last instruction in your program. therefore, your program can use any space below the address given in location 255. for example, if location 255 holds the value 100, then your program can use locations 0?99 for data. you can read location 255 at run-time or simply view the memory map of the program before you download it. on all bs2 models, you will need to view the memory map of the program before you download it to determine the last eeprom location used. see the memory map section of chapter 3. on the bs2p, bs2pe, and bs2px, the read and write commands can affect locations in any program slot as set by the store command. see the store command for more information. demo program (write.bs1) ' write.bs1 ' this program writes a few bytes to eeprom and then reads them back out ' and displays them in the debug window. ' {$stamp bs1} ' {$pbasic 1.0} symbol addr = b2 ' address symbol value = b3 ' value main: write 0, 100 ' write some data to locations 0 - 3 write 1, 200 write 2, 45 write 3, 28 read_ee: for addr = 0 to 3 read addr, value ' read value from address debug #addr, ": ", #value, cr ' display address and value next end 1
5: basic stamp command reference ? write basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 463 demo program (write.bs2) ' write.bs2 ' this program writes some data to eeprom and then reads them back out ' and displays the data in the debug window. ' {$stamp bs2} ' {$pbasic 2.5} idx var byte ' loop control value var word(3) ' value(s) main: write 0, 100 ' single byte write 1, word 1250 ' single word write 3, 45, 90, word 725 ' multi-value write read_ee: for idx = 0 to 6 ' show raw bytes in ee read idx, value debug dec1 idx, " : ", dec value, cr next debug cr ' read values as stored read 0, value debug dec value, cr read 1, word value debug dec value, cr read 3, value(0), value(1), word value(2) for idx = 0 to 2 debug dec value(idx), cr next end all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
write ? basic stamp command reference page 464 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
5: basic stamp command reference ? xout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 465 xout bs1 bs2 bs2e bs2sx bs2p bs2pe bs2px xout mpin, zpin, [ house \ command { \ cycles } { , house \ command { \ cycles } ? } ] function send an x-10 power-line control command (through the appropriate power-line interface).  mpin is a variable/constant/expression (0 ? 15) that specifies the i/o pin to output x-10 signals (modulat ion) to the power-line interface device. this pin will be set to output mode.  zpin is a variable/constant/expression (0 ? 15) that specifies the i/o pin that inputs the zero-crossin g signal from the power-line interface device. this pin will be set to input mode.  house is a variable/constant/expression (0 ? 15) that specifies the x- 10 house code (values 0 - 15 representing letters a through p).  command is a variable/constant/expression (0 ? 31) that specifies the command to send. values 0 ? 15 correspond to unit codes 1 ? 16. other commands are shown in table 5.125.  cycles is an optional variable/constant/expression (1 ? 255) specifying the number of times to transmit a given key or command. if no cycles argument is used, xout defaults to two. the cycles argument should be used only with the dim and bright command codes quick facts table 5.124: xout quick facts. all bs2 models compatible power-line interfaces pl-513 and tw-523 special notes the xout command will stop the basic stamp program until it is able to send the transmission. if there is no ac power to the power-line interface, the basic stamp program will halt forever. explanation xout lets you control appliances vi a signals sent through household ac wiring to x-10 modules. the appliances plugged into these modules can be switched on or off; lights may also be dimmed. each module is all 2
xout ? basic stamp command reference page 466 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com assigned a house code and unit code by setting dials or switches on the module. to talk to a particular module, xout sends the appropriate house code and unit code. the module with the corresponding code listens for its house code again followed by a command (on, off, dim, or bright). x-10 signals are digital codes imposed on a 120 khz carrier that is transmitted during zero crossings of the ac line. to send x-10 commands, a controller must synchronize to the ac line frequency with 50 s precision, and transmit an 11-bit code sequence representing the command. xout interfaces to the ac power-line through an approved interface device such as a pl-513 or tw-523 , available from x-10 dealers. the hookup requires a length of four-c onductor phone cable and a standard modular phone-base connector (6p4c type). connections are shown in figure 5.48. p0 vdd 10 k ? bottom of power-line interface (pl-513 or tw-523) p1 vss 1234 figure 5.48: xout power-line interface circuit. x-10 protocol details .
5: basic stamp command reference ? xout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 467 table 5.125 lists the xout command codes and their functions: table 5.125: xout commands and their function. command value function uniton %10010 turn on the currently selected unit. unitoff %11010 turn off the currently selected unit. unitsonf %11100 turn off all modules in this house code. lightson %10100 turn on all lamp modules in this house code. dim %11110 reduce brightness of currently selected lamp. bright %10110 increase brightness of currently selected lamp. note: in most applications, it?s not necessary to know the code for a given x-10 instruction. just use the command constant (uniton, dim, etc.) instead. but knowing the codes leads to some interesting possibilities. for example, xoring a uniton command with the value %1000 turns it into a unitoff command, and vice-versa. this makes it possible to write the equivalent of an x-10 ?toggle? instruction. here is an example of the xout instruction: mpin pin 0 ' modulation pin zpin pin 1 ' zero-cross input housea con 0 ' house code a = 0 unit1 con 0 ' unit code 1 = 0 xout mpin, zpin, [housea\unit1] ' get unit1's attention xout mpin, zpin, [housea\uniton] ' turn it on you can combine those two xout instructions into one like so: xout mpin, zpin, [housea\unit1\2, housea\uniton] ' unit 1 on. note that to complete the attention- getting code housea\unit1 we tacked on the normally optional cycles entry \2 to complete the command before beginning the next one. always spec ify two cycles in multiple commands unless you?re adjusting the brightness of a lamp module. here is an example of a lamp-dimming instruction: mpin pin 0 ' modulation pin zpin pin 1 ' zero-cross input housea con 0 ' house code a = 0 unit1 con 0 ' unit code 1 = 0 xout mpin, zpin, [housea\unit1] ' get unit1's attention xout mpin, zpin, [housea\unitoff\2] ' turn it off xout mpin, zpin, [housea\dim\10] ' dim half way c ombining multiple commands . d imming lights . a simple xout example : turning an appliance on .
xout ? basic stamp command reference page 468 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com the dim/bright commands support 19 brightness levels. lamp modules may also be turned on and off using the standard uniton and unitoff commands. in the example instruction above, we dimmed the lamp by first turning it completely off, then sending 10 cycles of the dim command. this may seem odd, but it follows the peculiar logic of the x-10 system. demo program (x10.bs2) ' xout.bs2 ' this program--really two program fragments--demonstrates the syntax and ' use of the xout command. xout works like pressing the buttons on an x-10 ' control box; first you press one of 16 keys to identify the unit you want ' to control, then you press the key for the action you want that unit to ' take (turn on, off, bright, or dim). there are also two group-action ' keys, lights on and all off. lights on turns all lamp modules on without ' affecting appliance modules. all off turns off all modules, both lamp and ' appliance types. connect the basic stamp to a power-line interface as ' shown in the xout command description in the manual. ' {$stamp bs2} ' {$pbasic 2.5} mpin pin 0 ' modulation pin zpin pin 1 ' zero-cross input housea con 0 ' house code a = 0 unit1 con 0 ' unit code 1 = 0 unit2 con 1 ' unit code 2 = 1 ' this first example turns a standard (appliance or non-dimmer lamp) module ' on, then off. note that once the unit code is sent, it need not be ' repeated ' --subsequent instructions are understood to be addressed to that unit. main: xout mpin, zpin, [housea\unit1\2] ' select unit1 (appliance module) xout mpin, zpin, [housea\uniton] ' turn it on pause 1000 ' wait one second xout mpin, zpin, [housea\unitoff] ' then turn it off ' the next example talks to a lamp module using the dimmer feature. dimmers ' go from full on to dimmed off in 19 steps. because dimming is relative to ' the current state of the lamp, the only guaranteed way to set a ' predefined brightness level is to turn the dimmer fully off, then on, ' then dim to the desired level. xout mpin, zpin, [housea\unit2\2] ' select unit2 (lamp module) all 2 note: this example program can be used with all bs2 models by changing the $stamp directive accordingly.
5: basic stamp command reference ? xout basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 469 ' this example shows the use of the optional cycles argument. here we dim ' for 10 cycles. xout mpin, zpin, [housea\unitoff\2, housea\dim\10] stop
xout ? basic stamp command reference page 470 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
appendix a: ascii chart basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 471 ascii chart (first 128 characters) dec hex char name / function dec hex char dec hex char dec hex char 0 00 nul null 32 20 space 64 40 @ 96 60 ` 1 01 soh start of heading 33 21 ! 65 41 a 97 61 a 2 02 stx start of text 34 22 " 66 42 b 98 62 b 3 03 etx end of text 35 23 # 67 43 c 99 63 c 4 04 eot end of transmit 36 24 $ 68 44 d 100 64 d 5 05 enq enquiry 37 25 % 69 45 e 101 65 e 6 06 ack acknowledge 38 26 & 70 46 f 102 66 f 7 07 bel bell 39 27 ' 71 47 g 103 67 g 8 08 bs backspace 40 28 ( 72 48 h 104 68 h 9 09 ht horizontal tab 41 29 ) 73 49 i 105 69 i 10 0a lf line feed 42 2a * 74 4a j 106 6a j 11 0b vt vertical tab 43 2b + 75 4b k 107 6b k 12 0c ff form feed 44 2c , 76 4c l 108 6c l 13 0d cr carriage return 45 2d - 77 4d m 109 6d m 14 0e so shift out 46 2e . 78 4e n 110 6e n 15 0f si shift in 47 2f / 79 4f o 111 6f o 16 10 dle data line escape 48 30 0 80 50 p 112 70 p 17 11 dc1 device control 1 49 31 1 81 51 q 113 71 q 18 12 dc2 device control 2 50 32 2 82 52 r 114 72 r 19 13 dc3 device control 3 51 33 3 83 53 s 115 73 s 20 14 dc4 device control 4 52 34 4 84 54 t 116 74 t 21 15 nak non acknowledge 53 35 5 85 55 u 117 75 u 22 16 syn synchronous idle 54 36 6 86 56 v 118 76 v 23 17 etb end transmit block 55 37 7 87 57 w 119 77 w 24 18 can cancel 56 38 8 88 58 x 120 78 x 25 19 em end of medium 57 39 9 89 59 y 121 79 y 26 1a sub substitute 58 3a : 90 5a z 122 7a z 27 1b esc escape 59 3b ; 91 5b [ 123 7b { 28 1c fs file separator 60 3c < 92 5c \ 124 7c | 29 1d gs group separator 61 3d = 93 5d ] 125 7d } 30 1e rs record separator 62 3e > 94 5e ^ 126 7e ~ 31 1f us unit separator 63 3f ? 95 5f _ 127 7f delete note that the control codes (lowest 32 ascii characters) have no st andardized screen symbols. the characters listed for them a re just names used in referring to these codes. for example, to move the cursor to the beginning of the next line of a printer or terminal often requires sending line feed and carriage return codes. this common pair is referred to as "lf/cr."
ascii chart page 472 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
appendix b: reserved words basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 473 reserved words this appendix contains complete listings of the reserved words for pbasic 1.0, pbasic 2.0, and pbasic 2.5, current with the basic stamp editor v2.1. the reserved word lists have been organized into 4 tables, because it varies with each basic stamp model and version of pbasic. table b.1 shows the reserved words for the basic stamp 1, using the required pbasic 1.0. table b.1: bs1 reserved words. bs1 and gosub n2400 pin0..pin7 sound b0..b13 goto nap pins step bit0..bit15 high next port symbol branch if on300 pot t300 bsave input on600 pulsin t600 button let on1200 pulsout t1200 cls lookdown on2400 pwm t2400 cr lookup or random then debug low ot300 read to dir0..dir7 max ot600 return toggle dirs min ot1200 reverse w0..w6 eeprom n300 ot2400 serin write end n600 output serout for n1200 pause sleep table b.2 on the following page lists the reserved words common to all bs2 models, including those for pbasic 2.0 and pbasic 2.5. words listed that are only reserved when using pbasic 2.5 are marked with ( 2.5 ).
reserved words page 474 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com all bs2 models #case 2.5 crsrx 2.5 inc pulsin #define 2.5 crsrxy 2.5 ind pulsout #else 2.5 crsry 2.5 inh pwm #endif 2.5 data inl random #endselect 2.5 dcd input rctime #error 2.5 debug ins read #if 2.5 debugin 2.5 isbin rep #select 2.5 dec isbin1...isbin16 return #then 2.5 dec1...dec5 ishex rev $pbasic dig ishex1...ishex4 reverse $port dim lf 2.5 sbin $stamp dir0...dir15 lightson sbin1...sbin16 abs dira lookdown sdec and dirb lookup sdec1...sdec5 asc dirc loop 2.5 select 2.5 atn dird low serin b0...b25 dirh lowbit serout bell dirl lowbyte shex bin dirs lownib shex1...shex4 bin1...bin16 do 2.5 lsbfirst shiftin bit dtmfout lsbpost shiftout bit0...bit15 else 2.5 lsbpre sin bksp elseif 2.5 max skip branch end min sleep bright endif 2.5 msbfirst snum bs1 endselect 2.5 msbpost sqr bs2 exit 2.5 msbpre step bs2e for nap stop bs2p freqout ncd str bs2pe gosub next tab bs2sx goto nib then button hex nib0...nib3 to byte hex1...hex4 not toggle byte0 high num unitoff byte1 highbit on 2.5 uniton case 2.5 highbyte or unitsoff clrdn 2.5 highnib out0...out15 until 2.5 clreol 2.5 home outa var cls hyp outb w0...w12 con ibin outc wait cos ibin1...ibin16 outd waitstr count if outh while 2.5 cr ihex outl word crsrdn 2.5 ihex1...ihex4 ouput write crsrlf 2.5 in0...in15 outs xor crsrrt 2.5 ina pause xout crsrup 2.5 inb pin 2.5 table b.2 reserved words common to all bs2 models. note: this list includes reserved words for both pbasic 2.0 and pbasic 2.5. words indicated with the symbol ( 2.5 ) are only reserved if used with pbasic 2.5.
appendix b: reserved words basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 475 there are some reserved words unique to specific bs2 models. the bs2e and bs2sx have all the reserved words shown in table b.2, plus those shown in table b.3. these addi tional words are reserved in both pbasic 2.0 and pbasic 2.5. table b.3: additional reserved words for the bs2e and bs2sx. bs2e and bs2sx get put run the bs2p and bs2pe have all the reserved words shown in table b.2, plus those shown in table b.4. these addi tional words are reserved in both pbasic 2.0 and pbasic 2.5. table b.4: additional reserved words for the bs2p and bs2pe. bs2p and bs2pe auxio lcdcmd owout pollwait get lcdin pollin put i2cin lcdout pollmode run i2cout mainio pollout spstr ioterm owin pollrun store the bs2px has all the reserved words shown in table b.2, plus those shown in table b.5. these additional words are reserved in both pbasic 2.0 and pbasic 2.5. table b.5: additional reserved words for the bs2px. bs2px auxio ioterm pollin run compare lcdcmd pollmode schmitt configpin lcdin pollout spstr direction lcdout pollrun store get mainio pollwait threshold i2cin owin pullup i2cout owout put
reserved words page 476 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
appendix c: conversion formatters basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 477 conversion formatters this appendix lists the conversion formatters available for the commands debugin, i2cin, lcdin, owin an d serin and demonstrates, through various input/output data examples, ex actly what will be received when using these formatters. the following tables show data examples (characters received) across the top and formatters across the left side , with the results of that combination shown in the target cell. for example, with the following code: value var word debugin sdec value the decimal formatters table shows us that if the characters -123 (followed by a carriage return) are received, the sdec formatter will translate that to the word-sized decimal number -123 and will store that value into the value variable. note: in all tables below, values in target cells represent the number base of the formatter (decimal for dec, he xadecimal for hex, etc) except where noted. additionally, ?--? means no valid data (or not enough valid data) was received so the command will halt forever unless additional data is received or serin?s timeout argument is used. table c.1 : decimal formatters. characters received decimal formatters ? 123 123 ? -123 ? ? 123 ? 12345 ? 65536 ? 255255 ? dec -- -- 123 123 123 12345 0 58647 dec1 -- 1 1 1 1 1 6 2 dec2 -- 12 12 12 12 12 65 25 dec3 -- 123 123 123 123 123 655 255 dec4 -- -- 123 123 123 1234 6553 2552 dec5 -- -- 123 123 123 12345 0 25525 sdec -- -- 123 -123 123 12345 0 -6889 sdec1 -- 1 1 -1 1 1 6 2 sdec2 -- 12 12 -12 12 12 65 25 sdec3 -- 123 123 -123 123 123 655 255 sdec4 -- -- 123 -123 123 1234 6553 2552 ? means any non-decimal-numeric characters such as letters, spaces, minus signs, carriage returns, control characters, etc. (decimal numerics are: 0,1,2,3,4,5,6,7,8 and 9).
conversion formatters page 478 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com characters received hexadecimal formatters ? 1f 1f ? -1f ? ? 1f ? 15af ? 10000 ? 3e517 ? hex -- -- 1f 1f 1f 15af 0 e517 hex1 -- 1 1 1 1 1 1 3 hex2 -- 1f 1f 1f 1f 15 10 3e hex3 -- -- 1f 1f 1f 15a 100 3e5 hex4 -- -- 1f 1f 1f 15af 1000 3e51 shex -- -- 1f -1f 1f 15af 0 -1ae9 shex1 -- 1 1 -1 1 1 1 3 shex2 -- 1f 1f -1f 1f 15 10 3e shex3 -- -- 1f -1f 1f 15a 100 3e5 table c.2 : hexadecimal formatters. note: the hex formatters are not case sensitiv e. for example, 1f is the same as 1f. ? means any non-hexadecimal-numeri c characters such as letters (greater than f), spaces, minus signs, carriage returns, control charac ters, etc. (hexadecimal numerics are: 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f). characters received additional hexadecimal formatters ? 1f 1f ? $1f $1f ? -$1f ? ? $1f ? $15af ? ihex -- -- -- -- 1f 1f 1f 15af ihex1 -- -- -- 1 1 1 1 1 ihex2 -- -- -- 1f 1f 1f 1f 15 ihex3 -- -- -- -- 1f 1f 1f 15a ihex4 -- -- -- -- 1f 1f 1f 15af ishex -- -- -- -- 1f -1f 1f 15af ishex1 -- -- -- 1 1 -1 1 1 ishex2 -- -- -- 1f 1f -1f 1f 15 ishex3 -- -- -- -- 1f -1f 1f 15a ishex4 -- -- -- -- 1f -1f 1f 15af table c.3 : additional hexadecimal formatters. note: the hex formatters are not case sensitiv e. for example, 1f is the same as 1f. ? means any non-hexadecimal-numeri c characters such as letters (greater than f), spaces, minus signs, carriage returns, control charac ters, etc. (hexadecimal numerics are: 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f). characters received binary formatters ? 11 11 ? -11 ? ? 11 ? 101 ? 3e517 ? bin -- -- 11 11 11 101 1 bin1 -- 1 1 1 1 1 1 bin2 -- 11 11 11 11 10 1 bin3 ? bin16 -- -- 11 11 11 101 1 sbin -- -- 11 -11 11 101 1 sbin1 -- 1 1 -1 1 1 1 sbin2 -- 11 11 -11 11 10 1 table c.4 : binary formatters. ? means any non-binary-numeric c haracters such as letters, spaces, minus signs, carriage returns, control characters, etc. (binary numerics are: 0 and 1).
appendix c: conversion formatters basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 479 table c.5: additional binary formatters. characters received additional binary formatters ? 11 11 ? %11 %11 ? -%11 ? ? %11 ? %101 ? ibin -- -- -- -- 11 11 11 101 ibin1 -- -- -- 1 1 1 1 1 ibin2 -- -- -- 11 11 11 11 10 ibin3 ? ibin16 -- -- -- -- 11 11 11 101 isbin -- -- -- -- 11 -11 11 101 isbin1 -- -- -- 1 1 -1 1 1 isbin2 -- -- -- 11 11 -11 11 10 isbin3 ? isbin16 -- -- -- -- 11 -11 11 101 ? means any non-binary-numeric c haracters such as letters, spaces, minus signs, carriage returns, control characters, etc. (binary numerics are: 0 and 1). table c.6: num and snum with decimal data. characters received general (dec. data) ? 123 123 ? -123 ? ? 123 ? 12345 ? 65536 ? 255255 ? num -- -- 123 123 123 12345 0 58647 ? means any non-decimal-numeric characters such as letters, spaces, minus signs, carriage returns, control characters, etc. (decimal numerics are: 0,1,2,3,4,5,6,7,8 and 9). table c.7: num and snum with hexadecimal data. characters received general (hex. data) ? 1f 1f ? $1f $1f ? -$1f ? ? $1f ? $15af ? num -- 1* 1* -- 1f 1f 1f 15af note: hexadecimal data is not case sensitive. for example, 1f is the same as 1f. ? means any non-hexadecimal-numeri c characters such as letters (greater than f), spaces, minus signs, carriage returns, control charac ters, etc. (hexadecimal numerics are: 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f). * invalid data; treated as decimal number one because no $ preceded it and non-decimal digit followed it. table c.8: num and snum with binary data. characters received general (bin. data) ? 11 11 ? %11 %11 ? -%11 ? ? %11 ? %101 ? num -- -- 11* -- 11 11 11 101 ? means any non-binary-numeric c haracters such as letters, spaces, minus signs, carriage returns, control characters, etc. (binary numerics are: 0 and 1). * invalid data; treated as decimal number eleven because no % preceded it.
conversion formatters page 480 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com
appendix d: basic stamp schematics basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 481 basic stamp 1 schematic (rev b)
basic stamp schematics page 482 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com basic stamp 2 schematic (rev g)
appendix d: basic stamp schematics basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 483 basic stamp 2e schematic (rev b)
basic stamp schematics page 484 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com basic stamp 2sx schematic (rev e)
appendix d: basic stamp schematics basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 485 basic stamp 2p24 schematic (rev c)
basic stamp schematics page 486 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com basic stamp 2p40 schematic (rev b)
appendix d: basic stamp schematics basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 487 basic stamp 2pe schematic (rev b)
basic stamp schematics page 488 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com basic stamp 2px schematic (rev a)
index basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 489 ? # ? #define, 71 #error, 75 #if...#then, 72 #select...case, 74 ? $ ? $pbasic directive, 32, 44?45 defaults, 44 required with syntax enhancements, 124 toolbar icons, 43 $port directive, 45?46, 50 $stamp directive, 32, 43?44 format, 43 toolbar icons, 43 with multi-file projects, 68 ? . ? .obj file, 76 ? 1 ? 1-wire protocol, 295?301, 303?10 ? 2 ? 24lc16b eeprom, 218, 226 ? a ? abs, 105 absolute value (abs), 105 accessing i/o pins, 81, 83, 84 add (+), 109 aliases, 89?91 aliases and variable modifiers, 89?91 amplifier, 180, 200, 446 analog i/o, 179, 199, 339, 355, 363, 445, see pwm, pot, rctime and, 235 and (&), 109, 118 and not (&/), 109, 120 architecture, 29, 81 arctangent (atn), 109, 114 arrays, 87?89 asc, 163 asc ?, 165, 228, 305, 422 ascii control characters (debug terminal), 66 display in debug terminal, 161, 163 display in memory map, 51 ascii chart, 471 ascii notation, 96 asynchronous serial, 394, 416, see also serin, serout, owin, owout atn, 109, 114 atn (pin), 14, 15, 18, 20, 21, 23 auto indent, 57 auxiliary i/o pins, 129, 247 auxio, 129?30, 247, 283 ? b ? b0-b13, 82 backup copy, 61 basic stamp architecture, 29, 81 hardware, 7 memory, 29, 81 networking, 425 pinouts, 8?20 reserved words, 473 basic stamp 1 rev. dx, 11 basic stamp projects. see multi-file projects
index page 490 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com basic stamp schematics, 481 basic stamp windows editor, 35 baud mode (table), 396, 418 baud mode, choosing, 397, 419 bell, 168 bin, 162, 163, 173, 220, 227, 260, 265, 298, 306, 403, 422 binary coded decimal, 97 binary notation, 96 binary operators, 104, 109?21 add (+), 109 and (&), 109, 118 and not (&/), 109, 120 arctangent (atn), 109, 114 digit (dig), 109, 117 divide (/), 109, 113 hypotenuse (hyp), 109, 115 maximum (max), 109, 116 minimum (min), 109, 115 modulus (//), 109, 113 multiply (*), 109, 110 multiply high (**), 109, 111 multiply middle (*/), 109, 112 or (|), 109, 118 or not (|/), 109, 120 reverse (rev), 109, 118 shift left (<<), 109, 117 shift right (>>), 109, 117 subtract (-), 109, 110 xor (^), 109, 119 xor not (^/), 109, 121 binary radian, 106, 107, 114 bksp, 168 board of education, 31 bookmarks, 38, 57 brad, 106, 107, 114 branch, 133?35, 289, 387 branching, 133?35, 137?40, 209?12, 213?14, 231?40, 289?90, 331?34, 375?76, 381?85, 387?90, see also branch, if...then, goto, gosub, on, return, run, pollrun, select...case bright, 467, see xout bs1 carrier board, 30 bs1 serial adapter, 27, 30 bs1-ic, 11 bs2-ic, 13 bs2p24-ic, 19 bs2p40-ic, 19 bs2px pin configuration function, 143 bs2px voltage comparison function, 141 bs2px24, 23 bs2sx-ic, 17 bsave, 76 button, 137?40 ? c ? cable (programming), 27 case. see select...case cgram, 252, 259, 266 character generator ram. see cgram clrdn, 168 clreol, 168 cls, 168 colons ( : ), 213 command line interface, 78?79 command line switches syntax, 78 comparator on bs2px, 141 compare, 141?42 comparison operators, 232, see operators, comparison compiler directives, 43?46 and conditional compilation, 70?75 see $stamp, $pbasic, $port, 43 compile-time expressions, 94?96, 98 con directive, 94, 99 conditional compilation, 70?75 conditional compile directives #define, 71 #error, 75 #if...#then, 72
index basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 491 #select...case, 74 conditional logic operators, 234, 235 configpin, 143?46 logic threshold mode, 144 output direction mode, 143 pull-up resistors mode, 144 schmitt trigger mode, 145 connecting & downloading, 29 connecting/disconnecting, 25, 27 constants, 94?96 defining and using, 94 operators in constant expressions, 96 control characters, 167 conversion formatters, 477?79 debugin, 173 i2cin, 220 i2cout, 227 lcdin, 260 owin, 298 owout, 306 serin, 403 serout, 422 cos, 105, 106 cosine (cos), 105, 106 count, 149?50 counter, 191 counting pulses, 149?50 cr, 168 crsrdn, 168 crsrlf, 168 crsrrt, 168 crsrup, 168 crsrx, 168 crsrxy, 168 crsry, 168 current limit, 12, 14, 15, 18, 20, 21, 23 cycle counting, 149 ? d ? data, 153?58, 459 writing block, 155 writing text strings, 156, 184 writing word values, 156, 185 data and program downloading, 155, 184 data input through debug terminal. see debugin dcd, 105, 106 ddram, 252, 258, 259 debounce buttons, 137 debug, 166 debug formatting (all bs2 models), 162 bs1, 160 debug port, 67 debug port preferences, 67 debug terminal, 51?53 appearance preferences, 65 buffer size, 64 choose?buttons, 63 control characters, 167 debug function preferences, 66 displaying strings, 166 echo off, 53 font size, 63 input data via transmit pane. see debugin port preferences, 67 receive pane, 52 repeating characters, 167 resizing, 63 tabs, 65 text wrapping, 64 transmit pane, 52 debugin, 159, 171?73 special formatters, 172 dec, 162, 163, 165, 173, 220, 227, 260, 265, 298, 306, 398, 403, 420, 422 decimal notation, 96 decoder (dcd), 105, 106 default com port, 60 default state, i/o pins, 83 default state, i/o pins (bs1), 82
index page 492 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com defining constants, 94?96 defining symbols, 85?91 delaying execution, 311 developer features, 75 dig, 109, 117 digit (dig), 109, 117 digital i/o, 129, 137, 143, 149, 215, 217, 225, 243, 247, 249, 257, 263, 281, 283, 293, 295, 303, 313, 325, 377, 393, 415, 431, 435, 455, 465 dim, 467, see xout direction (setting of i/o pins), 81, 83, 243, 293, 377 directives. see also conditional compile directives, see also $pbasic, $port, $stamp, see con, pin, var, data directory list, 40, 41 dirs, 83 dirs (bs1), 81 display data ram. see ddram displaying information, 159 displaying unsigned numbers, 164 divide (/), 109, 113 division remainder, 109, 113 do...loop, 175?77, 189 download function, 48?50 download time, saving, 60 ds1820 temperature sensor, 301, 308 dtmfout, 179?82 ? e ? echo, 47 echo off, 53 edit preferences debug function, 66 debug port, 67 debug terminal appearances, 63?65 editor appearance, 55?57 editor operation, 57?60 files and directories, 60?63 editing your code, 39 editor bookmarks, 38 described, 35 editor screen (diagram), 35 editor tabs, 35 find/replace function, 39 font size, 56 line numbers, 38 split window view, 36 status, 36 syntax highlighting, 37 windows, 35 editor appearance font size, 56 syntax highlighting, 56 editor functions command line interface, 78?79 debug terminal, 51?53 download function, 48?50 help files, 54 identification, 46?48 keyboard shortcuts, 53 memory map, 50?51 tip of the day, 55 eeprom, 183?86, 459 eeprom access. see eeprom, data, read, write, store eeprom map, 51 eeprom usage, 153, 369?73, 447 maximizing, 209 eeprom usage (bs1), 183 else. see select...case, see if...then elseif, 231, see if...then encoder (ncd), 105, 107 end, 187, 335, 447 endif. see if...then endselect. see select...case exit, 189 expressions, 94?96 expressions in constants, 96
index basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 493 ? f ? favorite directories, 63 features for developers, 75 file associations, 42, 61 file list, 40, 41 file management .obj file, 76 backup copy, 61 directory list, 41 favorite directories, 63 file associations, 42, 61 file list, 41 files and directories preferences, 63 filter list, 40, 41 initial directory, 62 keyboard shortcuts, 42 module directories, 62 open from, 41 recent list, 40 save to, 41 single executable file, 76 templates, 62 filter list, 40, 41 find/replace function, 39 firmware, 3 fixed plus smart tabs, 59 fixed tabs, 58 flow control, 409, 423 font size debug terminal, 63 editor pane, 56 for...next, 189 increment/decrement, 193 variables as arguments, 194 for?next, 191?97 formatters, conversion. see conversion formatters formatters, debug. see debug formatters formatters, special. see special formatters fpin, 409, 423 freqout, 199?201 ? g ? generating pulses, 347?49 generating random numbers, 359?61 generating sound (bs1), 445?46 generating sound (non-bs1), 199?201 get, 203?6 gosub, 209?12, 289, 375 goto, 209, 213?14, 213, 289 gui interface development, 78 guidelines and precautions, 25 ? h ? hardware basic stamp, 7 bs1, 10 bs2, 13 bs2e, 15 bs2p, 19 bs2pe, 21 bs2px, 23 bs2sx, 17 help files, 53?54 hex, 162, 163, 173, 220, 227, 260, 265, 298, 306, 403, 422 hex to bcd conversion, 97 hexadecimal notation, 96 high, 215?16, 281, 455 hitachi 44780 controller, 249, 258, 263 home, 168 hyp, 109, 115 hypotenuse (hyp), 109, 115 ? i ? i/o pin voltage comparator (bs2px), 141 i/o pin properties (bs2px), 143 i/o pins
index page 494 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com accessing, 81, 83, 84 auxiliary, 129, 247 default state, 83 default state (bs1), 82 defining with pin, 99 directions, 81, 83, 243, 293, 377 main, 247, 283 pin directive, 99?102 pinouts bs1, 12 bs2, 14 bs2e, 15 bs2p, 20 bs2pe, 21 bs2px, 23 bs2sx, 18 reading, 84 reading (bs1), 81 source/sink bs1, 12 bs2, 14 bs2e, 15 bs2p, 20 bs2pe, 21 bs2px, 23 bs2sx, 18 writing (bs1), 81 i 2 c protocol, 217?23, 225?30 i2cin, 217?23 i2cout, 225?30 ibin, 163, 173, 220, 227, 260, 265, 298, 306, 403, 422 identification function, 46?48 if...then, 231?40, 387 nested, 238 single vs multi-line syntax, 238 if?then, 133 ignore bs1 modules, 60 ihex, 163, 173, 220, 227, 260, 265, 298, 306, 403, 422 indent preferences, 57 initial directory on startup, 62 input, 243?44, 293, 377 ins, 83 integer math rules, 103, 104 integrated explorer panel, 40?42 resizing, 42 interface to telephone line, 181 interrupts not suppported by basic stamp, 331 inverse (~), 105, 106 ioterm, 129, 247?48, 283 isbin, 163, 173, 220, 227, 260, 265, 298, 306, 403, 422 ishex, 163, 173, 220, 227, 260, 265, 298, 306, 403, 422 ? k ? keyboard shortcuts coding functions, 53 editing and navigation, 39 editor functions, 53 file functions, 42 ? l ? labels, 213 language pbasic, 7 lcd commands, 251 lcd customer characters, 266 lcd displays, 249, 257, 263 lcd initialization, 251, 258, 264 lcdcmd, 249?56 lcdin, 257?61 lcdout, 263?70 let, 269 lf, 168 lightson, 467, see xout line numbering, 57 line numbers, 38 logic run-time, 96
index basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 495 logic level, ttl and cmos (diagram), 144 logic operators and, 235 not, 235 or, 235 xor, 235 logic threshold and bs2px, 143 cmos, 144 ttl, 144 logic truth tables, 235 lookdown, 133, 271?76 lookup, 271, 277?80 loop. see do...loop loopback, 47 loops, 175?77, 191?97, 213 conditional, 175?77 terminating, 189 low, 281?82, 455 low-power mode, 187, 285, 441?42 lsbfirst, 436 lsbpost, 432 lsbpre, 432 ? m ? main i/o pins, 247, 283 mainio, 129, 247, 283?84 mapping non-contiguous numbers, 275, 279 math integer math rules, 103 run-time, 96 max, 109, 116 maximum (max), 109, 116 measuring pulses, 343?45 measuring variable resistance, 339? 40, 363?68 memory, 29, 81 memory map, 44, 50?51, 91 (diagram), 50 ascii format, 51 eeprom map, 51 fixed variables, 51 hexadecimal format, 51 ram map, 50 memory organization, 81 min, 109, 115 minimum (min), 109, 115 modifiers, 89?91 module directories, 62 modulus (//), 109, 113 msbfirst, 436 msbpost, 432 msbpre, 432 multi-file projects project download modes, 70 multi-file projects, 68?70 $stamp directive, 68 creating, 69 multiply (*), 109, 110 multiply high (**), 109, 111 multiply middle (*/), 109, 112 ? n ? nap, 285?87, 335 ncd, 105, 107 negative (-), 105, 106 networking basic stamps, 425 next. see for...next non-volatile storage, 153 not, 235 num, 173, 220, 260, 298, 403 numbering systems, 94, 96 numbers, 94, 96 numbers, random. see random numerics. see let, lookup, lookdown, random ? o ? oembs1, 11 oembs2, 13
index page 496 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com oembs2sx, 17 on, 289?90, 375, 387 open baud modes, 425 open from, 41 open with, 62 operation, general theory, 7 operators binary, 104, 109?21 comaprison (select...case), 388 comparison (if...then), 232 comparison (lookdown), 273 conditional logic, 234 in constant expressions, 96 unary, 104, 105?9 or, 235 or (|), 109, 118 or not (|/), 109, 120 order of operations, 102?3 orientation, 25 output, 243, 293?94, 377 output direction and bs2px, 143 outs, 83 owin, 295?301 owout, 295, 303?10 ? p ? p0-p15, 14, 15, 18, 20, 21, 23 p0-p7, 12 pace, 421 pacing, 415 package types bs1, 10 bs2, 13 bs2e, 15 bs2p, 19 bs2pe, 21 bs2px, 23 bs2sx, 17 parallel i/o. see lcdcmd, lcdin, lcdout, see lcdcmd, lcdin, lcdout parentheses and order of evaluation, 103, 235 nested, 103 with expressions, 128 parity and parity errors, 407, 423 parity and timeout, 408 pause, 311 pbasic language, 7 pbasic language versions, 124 # of commands, 45 pbasic 2.5 enhancements., 124 reserved words, 473 pci, 12 pco, 12 pin directive, 99?102 pin-1 indicators, 25 pinmask, 143 pinouts bs1, 10 bs2, 13 bs2e, 15 bs2p, 19 bs2pe, 21 bs2px, 23 bs2sx, 17 pins, 81 pollin, 313?17, 319, 331, 335 pollmode, 313, 319?23, 331, 335 pollout, 313, 319, 325?28, 331, 335 pollrun, 313, 319, 331?34, 335, 381 pollwait, 313, 319, 331, 335?37 port, 81 port communication debug terminal preferences, 67 default com port, 60 port connection. see identify function pot, 339?40 potentiometer, 313?17, 363?68 power control, 187, 285?87, 335? 37, 441?42, see end, nap, sleep power supply bs1, 12 bs2, 14
index basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 497 bs2e, 15 bs2p, 20 bs2pe, 21 bs2px, 23 bs2sx, 18 powerline interface, 466 program debugging . see debug, debugin program slot, 68, 93, 203, 316, 320, 331, 351, 372, 381, 449, 459 programming connections, 27 programming environment, 35 projects. see multi-file projects protocol 1-wire, dallas, 295?301, 303?10 asynchronous rs-232, 393?412, 415?28 i 2 c, 217?23, 225?30 synchronous (spi), 431?34, 435?40 x10, 465?68 pull-up resistor and bs2px, 143 pull-up resistors (bs2px), 144 pulse width modulation, 355?58 pulses, generating, 347?49 pulses, measuring, 343?45 pulsin, 343?45 pulsout, 347?49 put, 351?52 pwm, 355?58 ? q ? quick start guide, 29 ? r ? radian, binary, 106, 107, 114 ram access. see get, put ram map, 50 ram organization bs1, 81 bs2, 82 bs2e, 82 bs2p, 82 bs2p40, 82 bs2pe, 82 bs2sx, 82 random, 359?61 random numbers, 359?61 rctime, 363?68 rctime equation, 365 read, 153, 369?73, 449, 459 reading potentiometers, 339?40, 363? 68 reading pulses, 149?50, 343?45 reading word values, 370 receive pane, 52 recent list, 40 reference notch, 26 registers memory map, 50 remainder of division, 109, 113 rep, 163, 167, 228, 305, 422 res, 12, 14, 15, 18, 20, 21, 23 reserved words additional bs2e and bs2sx, 475 bs2p and bs2pe, 475 all basic stam p 2 models, 474 basic stamp 1, 473 reserving eeprom locations, 155 reset, 12, 14, 15, 18, 20, 21, 23 return, 375?76 rev, 109, 118 reverse, 243, 293, 377?78 reverse (rev), 109, 118 rules of integer math, 103, 104 rules of symbols, 86 run, 331, 381?85 run-time, 98 run-time math and logic, 96
index page 498 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com ? s ? save to, 41 sbin, 163, 173, 220, 227, 260, 265, 298, 306, 403, 422 schematic bs1, 481 bs2, 482 bs2e, 483 bs2p24, 485 bs2p40, 486 bs2pe, 487 bs2px, 488 bs2sx, 484 schmitt trigger, 143, 145, 150 (diagram), 145 scratch pad ram registers, 93 scratch pad ram, 92, 203, 351?52 registers, 205 special purpose locations (pollmode), 323 sdec, 163, 173, 220, 227, 260, 265, 298, 306, 403, 422 select...case, 387?90 select?case, 387 serial port diagram, 395 serial timeout, 408, 425 serial troubleshooting, 410, 427 serin, 171, 393?412 serout, 415?28 shex, 163, 173, 220, 227, 260, 265, 298, 306, 403, 422 shift left (<<), 109, 117 shift right (>>), 109, 117 shiftin, 431?34 shiftout, 435?40 shortcuts. see keyboard shortcuts sin, 105, 107 sin (pin), 14, 15, 18, 20, 21, 23 sine (sin), 105, 107 single executable file, 76 skip, 172, 219, 259, 297, 404 sleep, 187, 335, 441?42 snum, 173, 220, 260, 298, 403 sound. see also sound, freqout, dtmfout sound, 445?46 sound, generation (bs1), 445?46 sound, generation (non-bs1), 199?201 sout, 14, 15, 18, 20, 21, 23 speaker, 180, 200, 446 special formatters debugin, 172 i2cin, 219 i2cout, 228 lcdin, 259 owin, 297 owout, 305 serin, 404 serout, 422 split window view, 36 spram. see scratch pad ram spstr, 219, 297, 404 spstr l, 172 sqr, 105, 108 square root (sqr), 105, 108 stamp directive. see $stamp directive stamploader.exe program, 76 static sensitive devices, 25 step. see for...next stop, 447 store, 449, 459 str, 163, 166, 172, 219, 228, 259, 297, 305, 404, 422 strings displaying, 166 subroutines, 209, 375 subtract (-), 109, 110 switching program slots, 381?85 symbol name rules, 86 symbols (characters). see + #, 161 $, 161 %, 161
index basic stamp syntax and reference manual 2.2 ? www.parallax.com ? page 499 &, 118 &/, 120 *, 110 *, 109 **, 109, 111 */, 109, 112 /, 109, 113 //, 109, 113 ?, 163, 165, 228, 305, 422 @, 154, 161 ^, 119 ^/, 121 |, 118 |/, 120 ~, 105, 106 +, 96, 109 <, 232 <<, 117 <=, 232 <>, 232 =, 232 >, 232 >=, 232 >>, 117 synchronous serial, 431?34, 435? 40, see also shiftin, shiftout< i2cin, i2cout syntax conventions, 128 syntax enhancements for pbasic 2.5, 124 syntax highlighting, 37, 56 customized, 57 pbasic versions, 45 ? t ? tab, 168 tables, 153?58, 183?86, 271?76, 277? 80 tabs (diagram), 59 character, 57 fixed plus smart tabs, 59 fixed tab positions list, 60 fixed tabs, 58 in debug terminal, 65 smart tabs, 58 tab behavior, 58?59 telephone touch tones, 179 templates, 62 text wrapping debug terminal, 64 theory of operation, 7 time. see pause, pollwait timeout, 393, 408, 415, 425 tip of the day, 55 to. see for...next toggle, 281, 455?57 tone generation, 179?82, 199?201, 445?46 transmit pane, 52 troubleshooting serial, 410, 427 truth table if...then, 235 pollin, 316 pollout, 327 two's compliment, 104 ? u ? unary operators, 104, 105?9 absolute value (abs), 105 cosine (cos), 105, 106 decoder (dcd), 105, 106 encoder (ncd), 105, 107 inverse (~), 105, 106 negative (-), 105, 106 sine (sin), 105, 107 square root (sqr), 105, 108 unit circle, 107, 114 unitoff, 467, see xout uniton, 467, see xout unitsonf, 467, see xout until. see do...loop untitled#, 36 usb port
index page 500 ? basic stamp syntax and reference manual 2.2 ? www.parallax.com and identify function, 48 ? v ? variable resistance, measuring, 339? 40, 363?68 variables aliases, 89?91 arrays, 87?89 defining, 85?91, 269 fixed, 84 modifiers, 89?91 sizes, 86 vdd, 12, 14, 15, 18, 20, 21, 23 versions, 3 vin, 12, 14, 15, 18, 20, 21, 23 voltage comparison function, of bs2px, 141 vss, 12, 14, 15, 18, 20, 21, 23 ? w ? w0-w6, 82 wait, 172, 259, 401, 404 waitstr, 172, 219, 259, 297, 404, 406 warranty, 2 while. see do...loop write, 153, 449, 459?63 ? x ? x0-x15, 20 x10 control, 465?68 xor, 235 xor (^), 109, 119 xor not (^/), 109, 121 xout, 465?68 xout command codes (table), 467


▲Up To Search▲   

 
Price & Availability of 28122

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X